Continuous sprite movement when key is held


(Brendyn Todd) #1

When I use this code my sprite only moves once then stops. I have to tap the key to keep moving. How can I write this so when it is held it will move continuously.

package 

{ import net.flashpunk.Entity; import net.flashpunk.graphics.Image; import net.flashpunk.graphics.Spritemap; import net.flashpunk.utils.Input; import net.flashpunk.utils.Key;

public class player extends Entity
{	
	
	[Embed(source = 'assets/KnightSheet.png')] private const PLAYER:Class;
	public var sprPlayer:Spritemap = new Spritemap(PLAYER, 16, 16)
	
	public function player(x:Number = 0, y:Number = 0) 
	{
		sprPlayer.add("WalkRight", [1, 2, 3, 4], 15, true);
		sprPlayer.add("WalkLeft", [6, 7, 8, 9], 15, true);
		sprPlayer.add("StandRight", [0], 15, true);
		sprPlayer.add("StandLeft", [5], 15, true);
		graphic = sprPlayer;
		
		sprPlayer.play("StandRight");
		
		this.x = x;
        this.y = y;
	}
	override public function update():void
	{
		if (Input.pressed(Key.RIGHT)) { x += 5 }
		if (Input.pressed(Key.LEFT)) { x -= 5 }
	}
}

}


(azrafe7) #2

Use Input.check() instead of Input.pressed().

  • Input.pressed() returns true if you just pressed the key (in the current frame)
  • Input.released() returns true if you just released the key (in the current frame)
  • Input.check() returns true if you’re holding the key down