Player Animations

Animating the Player

The Player has the following states:

  • Idle: The player is stationary and not moving.

  • Run: The player is actively moving either to the left or to the right.

  • Jump: The player is currently moving upwards after initiating a jump.

  • Fall: The player is moving downwards, typically due to gravity, after a jump or falling from a platform.

  • Hit: The player has been struck by an enemy or has fallen outside the boundaries of the map.

The current state of the player is determined by the context, which includes information such as the player's velocity, whether they are currently on the ground (is_on_ground), and their life status (is_dead).

game/player.h
// -----
// --- Add: Includes. ---
#include "engine/fsm.h"
#include "engine/sprite_sheet_animation.h"
#include "engine/state.h"
// --- End ---
// -----

class Player : public ng::Node {
// -----
private:
  // --- Add: Context and Player states. ---
  struct Context {
    sf::Vector2f velocity;
    bool is_on_ground = false;
    bool is_dead = false;
  };

  class IdleState : public ng::State<Context> {
   public:
    IdleState(ng::State<Context>::ID id, ng::SpriteSheetAnimation animation);

   protected:
    void OnEnter() override;

    void Update() override;

   private:
    ng::SpriteSheetAnimation animation_;
  };

  class RunState : public ng::State<Context> {
   public:
    RunState(ng::State<Context>::ID id, ng::SpriteSheetAnimation animation);

   protected:
    void OnEnter() override;

    void Update() override;

   private:
    ng::SpriteSheetAnimation animation_;
  };

  class JumpState : public ng::State<Context> {
   public:
    JumpState(ng::State<Context>::ID id, ng::SpriteSheetAnimation animation,
              const sf::SoundBuffer* sound_buffer);

   protected:
    void OnEnter() override;

    void Update() override;

   private:
    ng::SpriteSheetAnimation animation_;
    sf::Sound sound_;
  };

  class FallState : public ng::State<Context> {
   public:
    FallState(ng::State<Context>::ID id, ng::SpriteSheetAnimation animation);

   protected:
    void OnEnter() override;

    void Update() override;

   private:
    ng::SpriteSheetAnimation animation_;
  };

  class HitState : public ng::State<Context> {
   public:
    HitState(ng::State<Context>::ID id, ng::SpriteSheetAnimation animation,
             ng::Node* node, GameManager* game_manager);

   protected:
    void OnEnter() override;

    void Update() override;

   private:
    void Die();

    ng::SpriteSheetAnimation animation_;
    ng::Node* node_ = nullptr;
    GameManager* game_manager_ = nullptr;
  };
  // --- End ---

  // -----
  // --- Remove: The context has these already. ---
  sf::Vector2f velocity_;
  bool is_on_ground_ = false;
  bool is_dead_ = false;
  // --- End ---
  // --- Add: Context and FSM. ---
  Context context_;
  ng::FSM<Context> animator_;
  // --- End ---
};

Last updated