Here's a handy little snippet that extends sprites with a :slideTo
function. It's analogous to :moveTo
but animates with the provided duration and ease (or the defaults, if unspecified — the underscores in the argument names indicates they're optional). It leverages a timer under the hood, so it cleans up after itself and doesn't require anything apart from ensuring that playdate.timer.updateTimers()
gets called each frame.
function playdate.graphics.sprite:slideTo(x, y, _duration, _ease)
local start = playdate.geometry.vector2D.new(self.x, self.y)
local goal = playdate.geometry.vector2D.new(x, y)
if self._slider then self._slider:remove() end
self._slider = playdate.timer.new(_duration or 300, start, goal, _ease or playdate.easingFunctions.inOutCubic)
self._slider.updateCallback = function(t) self:moveTo(t.value:unpack()) end
end
Of course, this creates (and later destroys) a timer each time it's called, so I wouldn't use this in tight loops that run frequently, but it's great for simple little transitions.
Edit: Watch out for this bug if you're trying to animate something exclusively in the vertical axis: Value timers don't work with vectors when x component of both start and end values is zero
Edit 2: It turns out that recent changes in the 2.5 SDK prevent the use of vectors with Playdate easing functions, which means the above doesn't work at all anymore. Here's a revised version that works around it, albeit using separate timers for the X and Y animations.
function playdate.graphics.sprite:slideTo(x, y, _duration, _ease)
if self._sliderX then self._sliderX:remove() end
if self._sliderY then self._sliderY:remove() end
if x ~= self.x then
self._sliderX = playdate.timer.new(_duration or 300, self.x, x, _ease or playdate.easingFunctions.inOutCubic)
self._sliderX.updateCallback = function(t) self:moveTo(t.value, self.y) end
end
if y ~= self.y then
self._sliderY = playdate.timer.new(_duration or 300, self.y, y, _ease or playdate.easingFunctions.inOutCubic)
self._sliderY.updateCallback = function(t) self:moveTo(self.x, t.value) end
end
end