FSM vs State Pattern

I love both FSM and state pattern and the videos explain them pretty well (once you get your head around them) and I can see pro’s and con’s of each.

What would be good @sampattuzzi is to show how the best way to initiate an action during transition for both the FSM and the State Machine for completeness.

I think it’s fairly clear for the FSM where you put the code as you pop it in the Switch statement for each case and the video refers to it.

However I have implemented the State Machine that works well but can’t fathom the best way to take an action based on a transition for this model.

e.g. If we were writing the state for a simple car Reverse, Forward and Brake

    if (driveAmount < 0)
    {
        steerAmount = -steerAmount;
        Reverse();
    }
    else if (driveAmount > 0)
    {
        Forward();
    } else
    {
        Brake();
    }

and then we want to do something on the based on the state when it reverses

public class DriveReverse : BinLorryState
{

public void Forward(BinLorryContext context)
{
    context.SetState(new DriveForward());
}

public void Reverse(BinLorryContext context)
{
    Debug.Log("Still Reversing");
}

public void Brake(BinLorryContext context)
{
    context.SetState(new Stop());
}

}

A way I’ve seen is an Interface where there’s particular call backs.

So you have Tick(), TransitionIn(), TransitionOut() and each state handles it how it should. Does that make sense?

2 Likes

I labeled the state transitions in your other post here: How to Check the CurrentState?

I think Sam did breeze through this one, but in fairness he did say this course requires some OOP understanding. The “hard” part of this pattern is being able to trace what exactly is happening because it’s much more abstract.

Instead of an enum state variable you’re passing in yourself (this). Since you are (this is) a “context” you are and have a state variable that can be set (current state); this is synonymous with having an enum state variable.

Each class (reverse, forward, stop, etc.) is a state. The methods implemented within the class (forward, reverse, stop, etc.) are the transitions. These are the same as cases in a switch statement, just abstracted.

I would encourage you to very slowly trace by hand what is happening in this pattern. Walk through the code one step at a time as if you’re step debugging the code. Make sure you understand every line. If not, post here and someone will explain.

Thanks for taking the time to respond, I might add a Transition in / out from time to time as that would make sense.

Privacy & Terms