Problems with animation and input (SOLVED)

Hey guys, I’m new to this program, I’m getting stressed out because I can not understand where is my mistake. To make it easy for you guys, I created some sprites, I press the button to do the action, but the character does his animation in infinite loop and only stops when I press the same button again. I would like some code suggestion so I can press the button and the animation happens only as long as I hold the button and the character stops when I release the button. .

here is the piece of the code :

function on_input(self, action_id, action)
	if action_id == hash("go_right") and action.repeated == true then
		if self.currentAnimation == 1 then

			msg.post("#sprite","play_animation", {id = hash("run_right")})

			self.currentAnimation = 0
		else
			msg.post("#sprite","play_animation", {id = hash("idle")})
			self.currentAnimation = 1
		end
	
	elseif action_id == hash("go_left") and action.repeated == true then
		if self.currentAnimation == 1 then
			msg.post("#sprite","play_animation", {id = hash("run_left")})

			self.currentAnimation = 0
		else
				msg.post("#sprite","play_animation", {id = hash("idle")})
				self.currentAnimation = 1
		end	
		return true -- input handled.
	end
end

please help me as soon as possible!

Take a look at this example of how to play an animation while a character is moving:

CODE - https://github.com/britzl/publicexamples/tree/master/examples/play_animation
DEMO - http://britzl.github.io/publicexamples/play_animation/index.html

Some thoughts on why your code is not working:

  • on_input will be called many times, likely every frame, depending on settings in game.project
  • on_input will be called when a key is pressed (action.pressed == true), while the key is held down (action.repeated == true) and when the key is released (action.released == true)
  • The first time action.released is true it will start playing the idle animation and set self.currentAnimation to 1. (Assuming that self.currentAnimation starts with a value other than 1)
  • The second time action.released is true (the next frame) it will play the run_right animation and set self.currentAnimation to 0
  • The third time action.released is true it will go back to the behaviour of frame 1 and then continuously flip between these two states.
3 Likes

thank you so much, it worked correctly !!

2 Likes