Skip to content

State Machine

The StateMachine class manages different states of an object and transitions between them. It allows for switching between various states, updating the current state, and rendering the current state.

Constructor

new StateMachine();

Creates a new StateMachine instance.

  • Parameters: None

  • Returns: A new StateMachine instance.

  • Example:

    const stateMachine = new StateMachine();

Properties

  • states (object): A dictionary of states managed by the state machine. Each state is stored by its name as the key.
  • currentState (State): The currently active state in the state machine.

Methods

add(stateName, state)

Adds a new state to the state machine.

  • Parameters:

    • stateName (string): The name of the state to add.
    • state (State): An instance of the State class representing the state.
  • Returns: void

  • Example:

    stateMachine.add('idle', new IdleState());

change(stateName, [enterParameters])

Transitions to a different state, calling the exit() method of the current state and the enter() method of the new state.

  • Parameters:

    • stateName (string): The name of the state to transition to.
    • enterParameters (any, optional): Parameters to pass to the new state’s enter() method.
  • Returns: void

  • Example:

    stateMachine.change('running', { speed: 10 });

update(dt)

Updates the current state by calling its update() method.

  • Parameters:

    • dt (number): The time delta between frames, typically used for updating animations or physics.
  • Returns: void

  • Example:

    stateMachine.update(deltaTime);

render(context)

Renders the current state by calling its render() method.

  • Parameters:

    • context (CanvasRenderingContext2D): The canvas rendering context where the current state will be rendered.
  • Returns: void

  • Example:

    stateMachine.render(context);