function on_input(self, action_id, action) -- script function
local to = go.get_world_position() -- 1
local from = vmath.vector3(action.x, action.y, 0) -- 2
local angle = math.atan2(to.x - from.x, from.y - to.y) -- 3
local quat = vmath.quat_rotation_z(angle) -- 4
go.set_rotation(quat) -- 5
end
1.
This gets the world position of the game object the script is attached to.
go.get_position
get the local position of an object, meaning if its parent have been moved it will not report that.
2.
To understand what is happening here we first need to understand what the on_input does. on_input
is a defold standard function that defold run everytime you provide any type of input, be it touch/mouse or keyboard clicks.
action_id
holds the “name” of the input as defined in your input_bindings. We do do not check against that here, so it isn’t important for this example.
The action
variable holds a table consisting of values that are important to you when handling input, such as where on the screen the user is interaction (action.x and action.y).
Now for what it actually does, it creates a new vector with 3 axis (commonly refered to as x, y and z). Here x, y and z are set on creation, the values for x and y is used from the action
table. That means that the local from
variable will be set to where the user is touching.
3.
This get us the angle in radians using the arctan. It will gives us the angle given the ratio of the supplied arguments.
4.
We use the angle and convert it to a quaternion, they are used for rotations because Euler angles (“common angles”) are prone to gimbal locks and such issues.
5.
We now set the rotation of the game object the script is attached to.