Sprite rotation

There are three ways to rotate a sprite in Defold:

  1. Use the command go.animate. If you put this command in the init function and use a loop parameter the object will rotate continuosly while alive. This is the best method with the lowest CPU and memory overhead. Of course you could use this code in the update function too.
go.animate(".", "euler.z", go.PLAYBACK_LOOP_BACKWARD, 360, go.EASING_LINEAR, 60)
What does this code do?

go.animate is the command to animate an object.

"." means the current object

"euler.z" means rotate on the z axis. i.e. from the middle. Leonhard Euler: famous mathematician, look up his rotation theorem!

go.PLAYBACK_LOOP_BACKWARD means loop the animation continuously clockwise.

360 is the angle of the rotation: 360 degress is a full circle.

go.EASING_LINEAR means in one direction.

60 is the number of seconds it takes to make the full rotation.

Therefore this code rotates an object 360 degrees clockwise from the middle point, taking 60 seconds to make a complete rotation.

  1. Change the rotation angle of the sprite in each frame within the update function.
    This is a useful approach if you want full control of the animation in each frame, but it carries a larger overhead than using an animation method so should be avoided if the first suggested solution will work.
local rotation = go.get_rotation()
	go.set_rotation(rotation * vmath.quat_rotation_z(0.05 * dt))
What does this code do?

get_rotation will return the quaternion rotation relative to any parent object. Use get_world_rotation to return the global world rotation.

set_rotation sets the quaternion rotation. If we multiply the current angle by a number we can change the angle relative to the current position. Remember this should be multiplied by the delta time to ensure a consistent frame rate across different CPUs.

  1. Create a sequence of sprites for each frame of the rotation animation. Import these sprites into an atlas as an animation group.
    This should only be considered if there is no viable alternative. Sprites have a large overhead. If you want perfect animation you would need 360 sprites: one for each angle of rotation!