MAXScript 101_2.6 Collections and Arrays
1. Arrays
-- 1. Array definition
a = #(1, 3, 5, 7, 9)
-- 2. access array with loop
for i in a do print (sqrt i)
-- 3. get value
x = a[2] --3
-- 4. value is undefined when index is out of bound
y = a[23] --undefined
-- 5. can assign value when index is out of bound
a[10] = 42 -- a[6] 到 a[9] 为undefined, a[10] = 42
-- 6. append value to an array
append a 11 --给数组赋值
2. 获取一个数组,使用append or collect
1) append需要先定义数组
a = #()
for i in 1 to 10 do
if mod i 2 != 0 do append a i --a = #(1, 3, 5, 7, 9)
2) collect返回值为数组
roots = for i in 1 to 5 collect sqrt i --#(1.0, 1.41421, 1.73205, 2.0, 2.23607),
3) Example 1 for collect: Selection Loop
a = for i in 1 to 10 where mod i 2 != 0 collect i --where后跟关系表达式
4) Example 2 for collect
smallSpheres = for obj in geometry
where classOf obj == sphere and obj.numFaces < 50 --number of faces are for mesh
collect obj
3. 有关数组的实例1
--Visual MAXScript; 按spinner,球体的数目与半径会实时更新
rollout SphereTool3 "Spheres Creator 3" width:223 height:300
(
spinner count "Numuber: " pos:[30,33] width:118 height:16 range:[1,100,10] type:#integer
spinner growth "Radius Growth: " pos:[30,70] width:118 height:16 range:[1,100,10]
button create "Create Spheres" pos:[24,96] width:120 height:32
button del "Delete Spheres" pos:[24,144] width:128 height:48
--定义局部变量存储球,以便操作
local spheres = #()
-- 按下Create Spheres 按钮,创建sphere
on create pressed do
spheres = for i in 1 to count.value
collect sphere radius: (i *growth.value) position: [i^2*growth.value, 0, 0]
on del pressed do
(
for obj in spheres do
(
--对于数组spheres中没有被删除的物体,进行删除操作;
--这步判断是有必要的,否则数组spheres中无obj时,按该按钮会出现如下错误:
--Runtime Error: attempt to access deleted scene object
if Not isDeleted obj do delete obj
)
)
-- 对于增长系数growth发生变化时,只需要改变一下原来球体的半径大小和位置
on growth changed val do
for i in 1 to spheres.count do
(
spheres[i].radius = i * val
spheres[i].pos = [i ^ 2 * val, 0, 0]
)
-- 若改变了count值,场景中实时创建相应个数的球体
on count changed val do
(
delete spheres --若改变了count值,则删除原来的球体
create.pressed() --调用create pressed部分的代码,重新创建球体
)
)
createDialog SphereTool3
4.有关数组的实例2: 层级(hierarchy)
-- 将obj 及 obj的孩子都放入数组hierarchy中
fn addChildren obj hierarchy =
(
-- add object to the hierarchy array
append hierarchy obj
-- loop over children & recursively add their children
for child in obj.children do
addChildren child hierarchy
hierarchy -- as return value
)
-- Operations
c = addChildren $Box01 #() --收集Box01 及它的孩子
c = addChildren $Sphere01 c --将Sphere01 及它的孩子放入c中
select c --选择数组c中所有的物体
c.wireColor = red --将数组c中所有物体的wireColor改变为红色
视频教程:http://vimeo.com/19512311