l write following code to add cube rotation function as my study. but the method getting complex and hard to debug. This code have big problem . Is there more smart approach for this subject.?
function setup()
frame = 1
col={
color(32, 255, 0, 255),
color(237, 255, 0, 255),
color(0,0,255),
color(251, 251, 251, 255),
color(255, 115, 0, 255),
color(255, 0, 41, 255)
}
scene = craft.scene()
skyMaterial=scene.sky.material
skyMaterial.sky=color(157, 215, 223, 255)
skyMaterial.horizon=color(98, 165, 166, 255)
v=scene.camera:add(OrbitViewer, vec3(0,0,0), 80, 0, 200)
v.rx,v.ry=20,20
-- cubes table
-- cube[][1] sph instance
-- [2] current position
-- [3] current ratation angle
cubes={}
for x=-1,1 do
for y=-1,1 do
for z=-1,1 do
cp=vec3(x*5.05,y*5.05,z*5.05)
rt=vec3(0,0,0)
table.insert(cubes, {sph(cp.x,cp.y,cp.z),cp,rt})
end
end
end
dlt = 1
cyc =90
round=3600
rotvec=vec3(0,0,0)
rotvec.z =1
slice= -1
end
function rotateFlag(pos, vec, sl)
level=( pos.x* vec.x + pos.y* vec.y+ pos.z* vec.z)
if level > 0.5 and sl==1then
return true
elseif level < -0.5 and sl==-1 then
return true
elseif sl==0 and math.abs(level) < 0.5 then
return true
else
return false
end
end
function rotateAngle(ang, vec, agl)
ret= ang * vec+ agl
return ret.x,ret.y,ret.z
end
function scalarRotateAngle(ang, vec, agl)
ret= ang * vec
return ret.x - ret.y + ret.z
end
function stepAngle(ang,vec,agl)
return ang * vec + agl
end
function rotateInput(vec, stpos, sra)
if math.abs(vec.z)==1 then
ret = vec2(stpos.x, stpos.y)
rot=ret:rotate(math.rad(sra))
prod=vec3(rot.x,rot.y,stpos.z)
elseif math.abs(vec.y)==1 then
ret = vec2(stpos.z, stpos.x)
rot=ret:rotate(math.rad(sra))
prod=vec3(rot.x, stpos.y, rot.y)
elseif math.abs(vec.x)==1 then
ret = vec2(stpos.z, stpos.y)
rot=ret:rotate(math.rad(sra))
prod=vec3(stpos.x, rot.x,rot.y)
end
return prod
end
function update(dt)
for k,v in ipairs(cubes) do
if rotateFlag(v[1].position, rotvec,slice) then
sra = scalarRotateAngle(frame,rotvec,v[3])
v[1].rotation=quat.eulerAngles(rotateAngle(frame,rotvec,v[3]))
v[1].position= rotateInput(rotvec, v[2], sra)
if (frame % cyc) == 0 then
v[2]= rotateInput(rotvec,v[2], sra)
v[3] = stepAngle(90,rotvec,v[3])
-- print("v3=",v[2], v[3],v[1].position)
-- print(cubes[k][3].z)
end
end
end
scene:update(dt)
-- vary parameters for testing
-- frame : count draw() event
-- rotvec : rotation direction vector
-- must be either (0,0,1),(0,1,0),(1,0,0)
-- slice : cube group (1,?,?),(0,?,?), .....
if (frame % 90) == 0 then
frame=1
rotvec=vec3(rotvec.y, rotvec.z,rotvec.x)
rotvec=vec3(rotvec.y, rotvec.z,rotvec.x)
if rotvec.x == 1 then
slice = (slice + 1)
if slice==2 then
slice=-1
end
end
end
frame = frame + dlt
end
function draw()
update(DeltaTime*5)
scene:draw()
end
function sph(x,y,z)
c = scene:entity()
c.position=vec3(x,y,z)
c.model = craft.model.cube(vec3(5,5,5))
c.material = craft.material("Materials:Basic")
for z=1,#c.model.colors do
c.model:color(z,col[(z+3)//4])
end
return c
end