0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PlaydateAdvent Calendar 2022

Day 19

【Playdate】Animatorを使ってスプライトをアニメーションさせる

Posted at

sample_animator.gif
Animatorを使うことで指定した地点までの移動をスムーズに行うことができます。
今回は上記キャプチャのように離れたスプライトを中央に引き戻すAnimatorを実装します。

main.lua
import "CoreLibs/object"
import "CoreLibs/graphics"
import "CoreLibs/sprites"
import "CoreLibs/timer"

import "CoreLibs/animator"
import "CoreLibs/easing"

local gfx <const> = playdate.graphics

local playerSprite = nil

local animator = nil
local duration = 1000
local oldPoint = nil
local newPoint = nil

function myGameSetUp()

	local playerImage = gfx.image.new("Images/playerImage")
	assert( playerImage )

	playerSprite = gfx.sprite.new( playerImage )
	playerSprite:moveTo( 200, 120 )
	playerSprite:add()
	
	-- アニメーション
	oldPoint = playdate.geometry.point.new(200, 120)
	newPoint = playdate.geometry.point.new(200, 120)
	animator = gfx.animator.new(1, oldPoint, newPoint, playdate.easingFunctions.inBack)

	local backgroundImage = gfx.image.new( "Images/background" )
	assert( backgroundImage )

	gfx.sprite.setBackgroundDrawingCallback(
		function( x, y, width, height )
			backgroundImage:draw( 0, 0 )
		end
	)

end

myGameSetUp()

function playdate.update()
	if animator:ended() ~= true then
		playerSprite:moveTo( animator:currentValue() )
	end

	if playdate.buttonIsPressed( playdate.kButtonUp ) then
		playerSprite:moveBy( 0, -2 )
	end
	if playdate.buttonIsPressed( playdate.kButtonRight ) then
		playerSprite:moveBy( 2, 0 )
	end
	if playdate.buttonIsPressed( playdate.kButtonDown ) then
		playerSprite:moveBy( 0, 2 )
	end
	if playdate.buttonIsPressed( playdate.kButtonLeft ) then
		playerSprite:moveBy( -2, 0 )
	end
	
	if playdate.buttonIsPressed( playdate.kButtonA ) then
		if animator:ended() == true then
			local x, y = playerSprite:getPosition()
			oldPoint = playdate.geometry.point.new(x, y)
			animator = gfx.animator.new(duration, oldPoint, newPoint, playdate.easingFunctions.inBack)
		end
	end
	
	gfx.sprite.update()
	playdate.timer.updateTimers()

end

Animatorを使うにはimport "CoreLibs/animator"で読み込みます。
更にイージング関数が書いてあるimport "CoreLibs/easing"も読み込みます。
animatorgfx.animator.new(1, oldPoint, newPoint, playdate.easingFunctions.inBack)と指定したAnimatorを新規作成します。
第一引数がアニメーションするミリ秒、第二引数が始点、第三引数が終点、第四引数がイージングとなります。
(ここでアニメーションするミリ秒を1に指定しているのは、初期化のため)

playdate.update()にてAボタンが押されたときにアニメーションするようにしています。animator:ended()はアニメーションが再生済みかどうかをbool値で返します。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?