Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Haxe Flixel invincibility demo on a player character.
import flixel.util.FlxColor;
import flixel.FlxSprite;
class Player extends FlxSprite {
// Whether the player is invicible or not
public var isInvincible:Bool;
//The amount of time to be invincible for in seconds
public static inline var INVINCIBLE_TIME:Float = 1.5;
public function new(x:Float, y:Float) {
super(x, y);
isInvincible = false;
makeGraphic(16, 16, FlxColor.WHITE);
}
public function startInvincibility() {
isInvincible = true;
//When the time runs out, the player will no longer be invincible.
this.flicker(INVINCIBLE_TIME, 0.04, true, true, (_) -> {
isInvincible = false;
});
}
}
@KinoAR

This comment has been minimized.

Copy link
Owner Author

@KinoAR KinoAR commented Mar 17, 2021

Invincibility Example

This demonstrates how to make the user invincible temporarily.

The properties:

private var isInvincible:Bool;
public static inline var INVINCIBLE_TIME:Float = 1.5;

Setup the first properties you need for updating the state of the invincibility.

Next, the function startInvincibility handles the rest by starting it whenever you need it in your game and should last for 1 and a half seconds. See below

  public function startInvincibility() {
    isInvincible = true;
    //When the time runs out, the player will no longer be invincible.
    this.flicker(INVINCIBLE_TIME, 0.04, true, true, (_) -> {
      isInvincible = false;
    });

Here's how you would use it in game when the player gets hit.

	public function enemyTouchPlayer(enemy:Enemy, player:Player) {
                //Shakes the camera on touching the enemy
		FlxG.camera.shake(0.1, 0.1);
	
		// Touching an enemy always does 1 damage. Also starts the invincibility if it hasn't occurred yet.
		if (!player.isInvincible) {
			player.health -= 1;
			player.startInvincibility();
		}

		if (player.health <= 0) {
			player.kill();
		}
	}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment