Look at


Setup

This example shows how to rotate a game object to look at the mouse cursor. It reads the mouse position in on_input and uses the mathematical function math.atan2(x, y) to calculate the angle between the ray to the point to look at and the positive x-axis. This angle is used to set the rotation of the game object to always look at the mouse position.

Scripts

look_at.script

function init(self)
	-- make sure the script will receive user input
	msg.post(".", "acquire_input_focus")
end

function on_input(self, action_id, action)
	-- the position to look at (mouse/finger)
	local look_at = vmath.vector3(action.x, action.y, 0)
	-- own positon
	local my_position = go.get_position()

	-- calculate the angle that this object has to rotate to look at the given point
	local angle = math.atan2(my_position.x - look_at.x, look_at.y - my_position.y)
	-- set rotation as a quaternion
	go.set_rotation(vmath.quat_rotation_z(angle))
end

If you want to play with these examples, you can get the project on Github.

Do you want to see more examples? Why not write a few yourself and submit a pull request? We love contributions.

GITHUB