Skip to content
This repository was archived by the owner on Nov 16, 2025. It is now read-only.

FiniteStateMachine transitionTo()

ged edited this page Sep 10, 2024 · 4 revisions

Definition

Transitions the state machine to a specified state.

template<class TContext>
void transitionTo(FiniteStateMachine<TContext>::State& state, bool immediate = false);

Type Parameters

  • TContext: The type of the context, which holds data or behavior relevant to the state machine.

Parameters

  • state: The state to transition to.
  • immediate: Indicates whether the transition should happen immediately or in the next update cycle.

Remarks

The immediate parameter controls whether the transition occurs instantly or waits for the next update() call.
The current state's exit logic and the next state's enter logic are queued as part of the transition.
NOTE: if used within a callback function, multiple calls of transitionTo will result in only the last function call being the next state to transition to.

Usage

struct FooContext
{
...
static FiniteStateMachine<FooContext>::State state1;
static FiniteStateMachine<FooContext>::State state2;

FiniteStateMachine<FooContext>* fsm = nullptr;
...
};

auto ctx = FooContext();
auto fsm = FiniteStateMachine<FooContext>(&ctx);

ctx.fsm = &fsm;

fsm.transitionTo(FooContext::state1); // queues state1, to be executed in the next update cycle

fsm.transitionTo(FooContext::state1, true); // immediately transitions to state1, without the need to queue and wait for the next update cycle

// if used within a callback, it's best to only use a single call of 'transitionTo()'
static void update(FooContext* const ctx)
{
    ...
    ctx->fsm->transitionTo(FooContext::state1); // transitions to state1
    ...
}

// Multiple transitions controlled by a conditional statement is fine.
static void update(FooContext* const ctx)
{
    ...

    if (boolFlag)
    {
        ctx->fsm->transitionTo(FooContext::state1); // transitions to state1 if boolFlag is true
    }
    else
    {
        ctx->fsm->transitionTo(FooContext::state2); // transitions to state2 if boolFlag is false
    }

    ...
}

// Consecutive transitions will result to only the last transition being applied, so it's best avoid this case.
static void update(FooContext* const ctx)
{
    ...

    ctx->fsm->transitionTo(FooContext::state1); // state 1 will be overridden with state2 in the next line
    ctx->fsm->transitionTo(FooContext::state2); // state 2 is now the next state to transition

    ...
}

Clone this wiki locally