HaxeFlixel Logo HaxeFlixel Snippets
  • About
  • Tutorials
  • Back to HaxeFlixel.com
  • Basics
    • Screen
    • Adding
  • Objects
    • Alive
    • Health
  • Sprites
    • Making Sprites
    • Loading Sprites
    • Animation
    • Alpha
    • Color
    • Facing
    • Scale
    • Baked Rotations
  • Text
    • FlxText
    • FlxBitmapText
  • Movement
    • Velocity
    • Acceleration
    • MaxVelocity
    • Gravity
    • Jumping
    • Angle
    • Angular Velocity
    • Angular Acceleration
  • Groups
    • Basic Group
    • Typed Group
    • Recycling
  • Tiling
    • Tileblock
    • Tilemap
  • Overlap
    • Simple Overlap
    • Overlap Callbacks
  • Collision
    • 1-to-1 Collision
    • Immovable
    • Tilemap Collision
    • Moving Platforms
  • Camera
    • Flash
    • Fade
    • Shake
    • Follow
  • Input
    • Basics
    • Keyboard
    • Mouse
    • Button
  • Sound
    • FlxSound

Keyboard

keys is an instance of FlxKeyboard - a helper object that is used to track keyboard input.

if (FlxG.keys.anyPressed([UP]))
{
    sprite.velocity.y = -100;
}

Demonstration

Source

source/PlayState.hx

package;

import flixel.FlxG;
import flixel.FlxSprite;
import flixel.FlxState;
import flixel.ui.FlxVirtualPad;

class PlayState extends FlxState
{
    var sprite:FlxSprite;
    var pad:FlxVirtualPad;

    override public function create()
    {
        super.create();

        sprite = new FlxSprite("assets/sprite.png");
        sprite.screenCenter();
        add(sprite);

        pad = new FlxVirtualPad(FlxDPadMode.FULL, FlxActionMode.NONE);
        add(pad);
    }

    override public function update(elapsed:Float)
    {
        super.update(elapsed);

        var up:Bool = pad.buttonUp.pressed || FlxG.keys.anyPressed([UP, W]);
        var down:Bool = pad.buttonDown.pressed || FlxG.keys.anyPressed([DOWN, S]);
        var left:Bool = pad.buttonLeft.pressed || FlxG.keys.anyPressed([LEFT, A]);
        var right:Bool = pad.buttonRight.pressed || FlxG.keys.anyPressed([RIGHT, D]);

        if (up && down)
            up = down = false;
        if (left && right)
            left = right = false;

        if (up)
            sprite.velocity.y = -100;
        else if (down)
            sprite.velocity.y = 100;
        else
            sprite.velocity.y = 0;

        if (left)
            sprite.velocity.x = -100;
        else if (right)
            sprite.velocity.x = 100;
        else
            sprite.velocity.x = 0;
    }
}
View Source on GitHub

Tags

input keyboard
  1. Home
  2. Input
  3. Keyboard
Powered By HaxeFlixel Logo HaxeFlixel