Play animations

#1

Hello, I just downloaded the defold and I’m trying to re-create an atlas “walk” animation, when I receive an input, but I see that the play function is called constantly causing the animation to stop and only play after I release the input, how do I solve this?

Thanks for reading!

0 Likes

#2

Please share your code! I’m guessing that you are not checking action.pressed or action.released in on_input()

2 Likes

#3

To expand on my previous answer (I’ll create an example for this in the Examples page later):

function on_input(self, action_id, action)
	if action_id == hash("left") then
		if action.pressed then
			sprite.play_animation("#sprite", "walk")
		elseif action.released then
			sprite.play_animation("#sprite", "idle")
		end
	end
end
3 Likes

#4

I made the same code, but I had not put the released, should this work? I’ll try!

Thank you very much

1 Like

#5

Thank you very much the animation now works, but not 100%, when I receive two different inputs, and I release some input the animation is all messed up, what do I do?

0 Likes

#6

Start by showing the code so we can give advice!

1 Like

#7

0 Likes

#8

Ok, so with the logic you have you’ll play the idle animation as soon as any key is released. If you want to support multiple keys pressed at the same time, for instance pressing left+right at the same time and only play the idle animation when both are released you need to track that. Something like this:

local LEFT = hash("left")
local RIGHT = hash("right")

function init(self)
	-- we store input action pressed/released state here, keyed on action_id
	self.actions = {}
end

function on_input(self, action_id, action)
	if action.pressed then
		-- set pressed state for action_id to true
		self.actions[action_id] = true

		-- set direction, sprite flip and walk animation
		if action_id == RIGHT then
			self.direction.x = 8
			sprite.set_hflip("#Sprite", false)
			sprite.play_animation("#Sprite", "walk")
		elseif action_id == LEFT then
			self.direction.x = -8
			sprite.set_hflip("#Sprite", true)
			sprite.play_animation("#Sprite", "walk")
		end
	elseif action.released then
		-- clear pressed state for action_id
		self.actions[action_id] = false

		-- switch to idle animation if neither "left" or "right" is pressed
		if not self.actions[LEFT] and not self.actions[RIGHT] then
			sprite.play_animation("#Sprite", "idle")
		end
	end
end
2 Likes