Combining Shapes

Why Combine Shapes

So far, every model you’ve built has been one shape, sometimes rotated or moved, but always just one shape. What if you want an object made of several parts stuck together, like a body with a post sticking out of it? That’s what union(*shapes) is for: it takes several shapes and merges them into one.

That’s a flat base with a post rising out of the middle of it, but it’s one shape now, not two.

One Shape, Not Two

Notice base and post never show up on their own here, only the combined shape does. Here’s exactly what happened: union() built a brand new, third shape containing both of them, and that new shape is what took their place in the scene. base and post aren’t changed or destroyed. They still exist. They’re just not drawn separately anymore, because the new union already draws them, fused together.

This is the same “consumes what you give it” idea as rotate()/ translate() from the last lesson, just with two shapes going in instead of one. union() never mutates base or post to build its result. It always hands back something new.

You run a = Box(2, 2, 1), then b = Cylinder(0.5, 2, z=1), then c = union(a, b), and nothing else. What shows up in the scene?

Transforming the Whole Thing

Once two shapes are combined, the union is one real object, so you can rotate() or translate() it exactly like anything else, moving every part together.

u = union(Box(...), Cylinder(...)), then rotate(u, 45). What happens?

Growing a Union

What if you want to add a third piece later, without rewriting the whole union() call from scratch? Here’s the difference from before: u.add(shape) does not build a new shape. It changes u itself, in place, so anything else still pointing at u sees the new piece too.

Python has a shorthand for exactly this: +=. u += shape means the same thing as u.add(shape).

There’s also a plain +, without the equals sign, and it means something a little different: u + shape makes a brand new combined shape, the same as calling union(u, shape) – it doesn’t grow u itself. += is the one that changes u in place.

u = union(a, b), then u += c. What best describes what just happened?

Checking Your Work

Exercise: build a shape made of at least two parts combined into one with union() (or grown with +=) -- a base with a post, a body with a bump, anything you like -- so the whole combined shape ends up somewhere between 2 and 6 units tall.

Practice

That’s union(), how it consumes its arguments the same way rotate()/translate() do, transforming a combined shape as one object, and growing one with add()/+=. Next, the opposite idea: cutting shapes out instead of combining them.