I took one of my examples and stripped it down to just a camera and sphere. I added code for the look at calculations. I don’t understand any quat stuff, but I got it to work anyways. When the program starts, the camera and red sphere are randomly placed somewhere in a 400x400x400 area. When you tap the screen, the camera will rotate to look at the sphere. You can use the sliders to change the x,y,z positions of the camera and sphere. Tap the screen again to point the camera at the sphere. The x,y,z positions are displayed along with the camera quat values and camera to sphere distance.
viewer.mode=STANDARD
function setup()
print("slide window down")
assert(craft, "Please include Craft as a dependency")
parameter.integer("cxPos",-200,200,math.random(-200,200))
parameter.integer("cyPos",-200,200,math.random(-200,200))
parameter.integer("czPos",-200,200,math.random(-200,200))
parameter.integer("sxPos",-200,200,math.random(-200,200),createSphere)
parameter.integer("syPos",-200,200,math.random(-200,200),createSphere)
parameter.integer("szPos",-200,200,math.random(-200,200),createSphere)
direction=vec3(0,0,0)
scene = craft.scene()
skyMaterial = scene.sky.material
skyMaterial.horizon = color(0, 203, 255, 255)
createSphere()
fill(255)
end
function update(dt)
scene:update(dt)
scene.camera.position=vec3(cxPos,cyPos,czPos)
end
function draw()
background(0)
update(DeltaTime)
scene:draw()
dist()
text("Sphere position x="..sxPos.." y="..syPos.." z="..szPos,WIDTH/2,HEIGHT-50)
text("Camera position x="..cxPos.." y="..cyPos.." z="..czPos,WIDTH/2,HEIGHT-100)
text("Camera quat direction x="..direction.x.." y="..direction.y.." z="..direction.z ,WIDTH/2,HEIGHT-125)
text("Distance from camere to sphere "..distance,WIDTH/2,HEIGHT-150)
text("Tap screen to point camera at sphere",WIDTH/2,HEIGHT-250)
text("Move sliders to change camera and sphere positions",WIDTH/2,HEIGHT-280)
end
function createSphere()
if sphere then
sphere:destroy()
end
sphere=scene:entity()
sphere.model = craft.model.icosphere(2,3)
sphere.position=vec3(sxPos,syPos,szPos)
sphere.material = craft.material(asset.builtin.Materials.Specular)
sphere.material.diffuse=color(255,0,0)
end
function touched(t)
if t.state==BEGAN then
rotateCamera()
end
end
function rotateCamera()
local diff=-(scene.camera.position-sphere.position):normalize()
direction=quat.lookRotation(diff,vec3(0,1,0))
scene.camera.rotation=direction
end
function dist()
c,s=scene.camera.position,sphere.position
distance=math.sqrt((c.x-s.x)^2+(c.y-s.y)^2+(c.z-s.z)^2)
end