How do I play animation only when the key is pressed?

Hello everyone, I am new to Defold and this is my first game project. I was working on the Defold player script, which reads inputs from the user and accordingly plays the appropriate animation.

This is my player.script:

function init(self)
	msg.post(".","acquire_input_focus")
	self.runSpeed = 50
	self.curAnim = "idle"
	msg.post("#idle", "play_animation", { id=hash("idle") })
	self.speed = vmath.vector3()
end

function update(self, dt)
	local pos = go.get_position()
	if self.speed.x ~= 0 then    
		pos = pos + self.speed * dt
		go.set_position(pos)

		if self.curAnim ~= "run" then
			msg.post("#idle", "play_animation", { id=hash("run") })
			self.curAnim = "run"
		end
	end
end

function on_input(self, action_id, action)
	if action_id == hash("MOVE_RIGHT") then
		self.speed.x = self.runSpeed
		sprite.set_hflip("#idle", false)
		
	if action_id == hash("MOVE_LEFT") then
		self.speed.x = self.runSpeed * -1
		sprite.set_hflip("#idle", true)
	end      
end

The problem is that when I build the game and press the right key or the left key, the character keeps on running and eventually goes away from the camera screen. Can anyone please tell me what I am doing wrong?

Output:

As you can see, I just pressed the left key once and the character moved away from the screen.

You are never setting self.speed.x to 0. Key actions (and mouse and game pad buttons) generate one pressed event on the first frame of an action and a released event on the last frame. More here:

Example of mouse pressed/released:

So one solution is that you set the self.speed.x value when you detect action.pressed and set it to 0 when you detect action.released. Another solution is that you set self.speed.x to 0 every frame in update(), like in this example:

5 Likes