Skip to content

Instantly share code, notes, and snippets.

@RichardBray
Last active September 1, 2020 09:01
Show Gist options
  • Save RichardBray/7347fa48ba80ba3a8b75ec0a0abc8dab to your computer and use it in GitHub Desktop.
Save RichardBray/7347fa48ba80ba3a8b75ec0a0abc8dab to your computer and use it in GitHub Desktop.
An example file on how to use FlxFSM. A bit simpler than the example from the demo on the HaxeFlixel site.
import flixel.FlxG;
import flixel.FlxObject;
import flixel.FlxSprite;
import flixel.addons.util.FlxFSM;
/**
* Example of how to use the FlxFSM addon.
* For more informtaion on this file check this youtube video.
*
* @see Video-TBA
*
*/
class Player extends FlxSprite {
public final SPEED = 250;
public final WALKING_SPEED = 100;
public final GRAVITY = 600;
public var left = false;
public var right = false;
public var walk = false;
var jump = false;
var touchingFloor = false;
var fsm:FlxFSM<Player>;
public function new(x:Int = 0, y:Int = 0) {
super(x, y);
fsm = new FlxFSM<Player>(this);
fsm.transitions.add(Grounded, Jumping, (_) -> jump && touchingFloor)
.add(Jumping, Grounded, (_) -> touchingFloor)
.start(Grounded);
loadGraphic("assets/images/kenny_male.png", true, 96, 128);
drag.x = SPEED * 4;
animation.add("run", [for (i in 25...28) i], 12);
animation.add("walk", [for (i in 36...44) i], 12);
animation.add("jump", [2], 12, false);
animation.add("idle", [0], 12, false);
setFacingFlip(FlxObject.LEFT, true, false);
setFacingFlip(FlxObject.RIGHT, false, false);
acceleration.y = GRAVITY;
}
public function movement(speed:Int) {
if (left && right) {
velocity.x = 0;
} else {
velocity.x = right ? speed : -speed;
facing = right ? FlxObject.RIGHT : FlxObject.LEFT;
}
}
override function update(elapsed:Float) {
touchingFloor = isTouching(FlxObject.FLOOR);
fsm.update(elapsed);
super.update(elapsed);
left = FlxG.keys.anyPressed([LEFT, A]);
right = FlxG.keys.anyPressed([RIGHT, D]);
jump = FlxG.keys.anyPressed([UP, SPACE, W]);
walk = FlxG.keys.pressed.SHIFT;
}
}
class Jumping extends FlxFSMState<Player> {
override public function enter(player:Player, _) {
player.velocity.y = -player.GRAVITY / 1.5;
}
override public function update(_, player:Player, _) {
player.animation.play("jump");
if (player.left || player.right) player.movement(250);
}
}
class Grounded extends FlxFSMState<Player> {
override public function update(_, player:Player, _) {
if (player.left || player.right) {
player.animation.play(player.walk ? "walk" : "run");
player.movement(player.walk ? 100 : 250);
} else {
player.animation.play("idle");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment