OpenSCAD支持变量和循环,从而可以快速复制出大量的几何对象并且按照递归的方式进行布局。
循环的变量可以是枚举、区间和矢量对象,循环体支持几何对象构建、坐标平移与旋转、交并差等操作。
Vector(矢量):
for (variable=<vector>) { <do_something> - <variable> is assigned to each successive value in the vector }
Range(区间、范围):
for (variable=<range>) { <do_something> }
Nested(嵌套) :
for ( variable1 = <range or vector>, variable2 = <range or vector> ) { <do something, using both variables> }
for 循环可以进行嵌套,就像普通程序一样。
Usage example 1 - 通过vector的循环调用 | |
for (z = [-1, 1]) // 两个变量, z = -1, z = 1 { translate([0, 0, z]) cube(size = 1, center = false); } |
使用范围型变量的循环 |
Usage example 2a - 通过范围实现循环 | |
for ( i = [0 : 5] ) { rotate( i * 360 / 6, [1, 0, 0]) translate([0, 10, 0]) sphere(r = 1); } |
使用范围型给定步长的循环 |
Usage example 2b -指定步长和范围的循环 |
// Note: The middle parameter in the range designation // ('0.2' in this case) is the 'increment-by' value // Warning: Depending on the 'increment-by' value, the // real end value may be smaller than the given one. //类似于c语言的for(i=0;i<5;i+=0.2)... for ( i = [0 : 0.2 : 5] ) { rotate( i * 360 / 6, [1, 0, 0]) translate([0, 10, 0]) sphere(r = 1); } |
Usage example 3 - 通过矢量的循环 (旋转) | |
for(i = [ [ 0, 0, 0], [ 10, 20, 300], [200, 40, 57], [ 20, 88, 57] ]) { rotate(i) cube([100, 20, 20], center = true); } |
通过矢量数组的枚举型循环 |
Usage example 4 -矢量数组的循环(位移): | |
for(i = [ [ 0, 0, 0], [10, 12, 10], [20, 24, 20], [30, 36, 30], [20, 48, 40], [10, 60, 50] ]) { translate(i) cube([50, 15, 10], center = true); } |
循环的嵌套和多变量 |
嵌套循环的例程
for (xpos=[0:3], ypos = [2,4,6]) // do twelve iterations, using each xpos with each ypos translate([xpos*ypos, ypos, 0]) cube([0.5, 0.5, 0.5]);
所有的循环(包括枚举值、范围、矢量、矢量数组)都支持几何实体的 intersection 操作。
注意: intersection_for()
is a work around because of an issue that you cannot get the expected results using a combination of the standard for()
and intersection()
statements. The reason is that for()
do a implicit union()
of the contents.
参数
<loop variable name>
Name of the variable to use within the for loop.
Usage example 1 - 范围循环: | |
intersection_for(n = [1 : 6]) { rotate([0, 0, n * 60]) { translate([5,0,0]) sphere(r=12); } } |
Intersection for使用示例: |
Usage example 2 - rotation : | |
intersection_for(i = [ [ 0, 0, 0], [ 10, 20, 300], [200, 40, 57], [ 20, 88, 57] ]) { rotate(i) cube([100, 20, 20], center = true); } |