Keyboard Input (Flixel)

From Flash Game Dojo

Jump to: navigation, search
Flixel.png
More Snippets
Flixel
FlashPunk

FlxG has a collection of global variables and references, including a keys object that can check whether or not a key has been pressed. There are a variety of ways to check for keyboard input, as illustrated below. You might also be interested in learning about How do I check for mouse input?(Flixel) or How do I set up a gamepad?(Flixel)

override public function update():void
{
	//Quick check:
	if(FlxG.keys.SPACE)
	{
		//Space bar is currently pressed.
	}
	
	//Check if the button was just pressed:
	if(FlxG.keys.justPressed("SPACE"))
	{
		//User just pressed the space bar.
	}
	
	//Check if the button was just released:
	if(FlxG.keys.justReleased("SPACE"))
	{
		//User just let go of the space bar.
	}
	
	super.update();
}

NumberPad: On a keyboard, 0 is different from numpad 0. Unfortunately, the way flixel's keyboard system works means that you can't listen for both keypresses with the same constant.

In the beta and dev branches, you can now check FlxG.keys.ZERO or FlxG.keys.NUMPADZERO. Pretty much anything else on the numpad is prepended with NUMPAD, such as NUMPADSLASH or NUMPADPLUS. (Special thanks to User:Cai for this note)

ADVANCED: You can also use a string alias to look up a key state, which can be handy - especially in complex, multiplayer, or reconfigurable-button games.

override public function update():void
{
	var jump:String = "SPACE";
	if(FlxG.keys[jump])
	{
		//The 'jump' button is currently pressed
	}
	
	super.update();
}

See Also

Personal tools