Animating rotation (DEF-1636) (SOLVED)

After contemplating your answer @Ragnar_Svensson

I’ve decided that currently it’s not possible to do this using only go.animate, since euler animations are limited to the 360 degrees available and Slerp isn’t an option. So for now I’ll resolve to this system.

go.property("move_speed", 10)
go.property("turn_speed", 0.1)

function update(self, dt)
	if self.target_rotation then
		local rot = vmath.slerp(dt*self.turn_speed, go.get_rotation(), self.target_rotation)
		go.set_rotation(rot)
	end
end

function on_message(self, message_id, message, sender)
	if message_id == hash("move_to") then
		local direction = go.get_world_position() - message.position
		if vmath.length_sqr(direction) == 0 then
			-- avoid repeated navigation and NAN values from 0 distance.
			return
		end

		-- Rotate to face target position
		local forward = vmath.normalize(direction)
		local rotation_z = math.atan2(forward.y, forward.x)
		self.target_rotation = vmath.quat_rotation_z(rotation_z)
		
		-- Move to target position
		local distance = vmath.length(direction)
		local duration = distance / self.move_speed
		local turn_delay = 1 / self.turn_speed
		go.cancel_animations(".", "position")
		go.animate(".", "position", go.PLAYBACK_ONCE_FORWARD, message.position, go.EASING_LINEAR, duration, turn_delay, function()
			msg.post(".", "stop")
		end)
	end
end

If the underlying system could support Slerp for the “rotation” property that would be amazing :slight_smile:

4 Likes