Combining objects
Displaying multiple shapes
If you tried calling output a second time, you will have noticed that is overwrites the previous call. For example:
from openscad import *
# Create a cube and a cylinder
cu = cube([5,5,5])
cy = cylinder(5)
# We display the cube
output(cu)
# We display the cylinder, which overwrites the previous output call
# THE CUBE IS NO LONGER DISPLAYED
output(cy)
So how do we display multiple shapes? Simple! We pass them all to the output function using a list:
from openscad import *
# Create a cube and a cylinder
cu = cube([5,5,5])
cy = cylinder(5)
# Both objects are now displayed at once
output([cu,cy])
Combining objects with union()
Lets say you wanted to merge 2 objects into one, how could you do that?
Well, you combine them with the union()
method:
One important thing to note is the fact the union()
does NOT edit the objects in place. Rather, it creates a third brand new object.
This means that:
- You must assign the union to a variable, just calling
cu.union(cy)
alone will have no effects oncu
orcy
. - You keep access to the originals objects. For example, you could still display just the cube by using
output(cu)
Substracting objects with difference()
You learned how to merge two objects into one, but what if you want to exclude an object from another?
For that, you can use the difference()
method:
As you can see, this creates a cylinder-shaped hole in the cube!
Using operators
Using the union
and difference
method works great, but is a little heavy synthax-wise.
You can instead simplify it by using operators!
Operators can also be used to easily translate or scale solid
Here is a table detailing which operator matches each method:
Operator | Method |
---|---|
| | union two solids |
- | difference two solids |
& | intersection of two solids |
* | scale an solid with a value or a vector |
+ | translate an solid with a vector |
So, reusing our earlier examples, you could write
from openscad import *
cu = cube([5,5,5])
cy = cylinder(5)
# Replaces cu.union(cy)
fusion = cu | cy
output(fusion)
There are some more conveniance function to translate or rotate objects.
from openscad import *
result = obj1.right(1).down(2) # directions are right, left, front, back, up, down
result2 = obj2.rotz(30) # 30 degrees, there is rotx, roty, rotz
Now that we know how to combine objects, lets see how we can position them.