
In the tutorials so far, we’ve got some basic CSG working, it’s time to start using the more powerful tools that combine the CSG toolset with a programming toolset. First, constants. Constants are defined in the same way as variables in C or Java, although they don’t have types since they’re all floating-point numbers:
x=20;
sphere(x);
translate([0,0,-x*1.7])sphere(2*x);
A word of warning though, these aren’t variables in the classical sense. If you want to change them halfway through a file, you’re out of luck. A second declaration will overwrite instances of that variable, including those earlier in the file. The following code:
x=20;
sphere(x);
x=10;
translate([20,0,0])sphere(x);
Will actually produce two spheres of the SAME size, 10. (This doesn’t apply to the arguments of modules, however, so if you need to reproduce the same object with different parameters in the same file, you can use those.)
Another great tool is the for loop. For loops are another staple of the programming world, and in their simplest form you can use them to drop down the same shape repeatedly with some (or many) parameters changed as a function of the “iteration variable”, in the case below, i:
union(){
for (i = [0:19]){
rotate([0,0,i*360/20])translate([-50,0,0])sphere(10);
}
}
The above loop sweeps the sphere around in a circle to create a ring of spheres. For each value of i from 0 to 19, a new sphere is placed with a different rotation. (The translate step moves the sphere so that the rotate step is rotating it around a point 50 units off center.) Neat, huh? This is a great tool for adding details like ridges, or for creating mathematically defined shapes.
With different notation, the for loop can also be given a sequence of discrete values:
for (i = [3, 5, 7, 11]){
rotate([i*10,0,0])scale([1,1,i])cube(10);
}
Here, we rotate and scale a cube by a set of primes.
The for loop works in OpenSCAD with the CSG toolset, so you can union or difference objects generated by for loops to create complex structures. (You can use intersections as well, but you’ll have to use the workaround described in the documentation.)