
Our challenge was:

how to drag the button that opens the door, and "install" it in the lateral wall?
We find some code in the internet and make some modifications - the Lavoisier law :-)
We define the key p to be the key to be pressed when the pointer/cursor is over the button, to pick it. DON'T CLICK THE BUTTON! ONLY PUT THE POINTER OVER! Dragging the cursor we drag the object.
We define the keys: k and l to be pressed to rotate the button.
And the new code in the avatarobj script is:
-- etc.etc.
on control me
--NEW!
if keypressed("p") then
-- Find where the mouse is
spriteLoc = the mouseLoc - point(sprite(1).left,sprite(1).top)
-- Find the button and camera in the 3D world
butLoc = myworld.model("but").worldPosition --button position
cameraLoc = cameraobj.mycam.worldPosition
-- Find a (distant) point beneath the mouse, in the world
distantLoc = cameraobj.mycam.spriteSpaceToWorldSpace(spriteLoc)
-- Create an imaginary line between the user's eye and this point
ray = distantLoc - cameraLoc
-- We need to work with a vector whose length is 1 unit
ray.normalize()
-- Determine which axis the camera is looking along
cameraAxis = cameraobj.mycam.transform.zAxis
-- Do a little mathematics, based on the fact that the dotProduct of
-- two perpendicular vectors is zero.
vectorToBut = butLoc - cameraLoc
distanceToBut = (vectorToBut * cameraAxis) / (ray * cameraAxis)
newLoc = cameraLoc + (ray * distanceToBut)
-- Move the button
myworld.model("but").transform.position = newLoc
end if
--rotating the button
if keypressed("k") then
turno = 2
else
if keypressed("l") then
turno = -2
else
turno = 0
end if
end if
steero = (steero + turno)*0.8
if steero < -5.0 then steero = -5.0
if steero > 5.0 then steero = 5.0
-- for button rotation
myworld.model("but").transform.rotate(myworld.model("but").worldposition, upvect, steero)
-- old code
if keypressed(126) then
acc = 2
else
acc = 0
end if
--etc. etc.
Play the demo. To pick the red button: mouseover the button and press the key: p. DON'T CLICK THE BUTTON! To move the button, drag the pointer/cursor. To let the button free: no more press the p key. To rotate the button: press the keys: k or l. The chalenge: "to install" the button in the lateral wall. The function of the button remains: clicking it you will open the door!
PREVIOUS LESSON NEXT LESSON T. CONTENTS HOMEPAGE
