How to design a state machine?

Started by
4 comments, last by lucky6969b 12 years, 5 months ago
I'd like to define a state machine that returns the next state of an entity for animation purposes. Where should I be starting to look at? [Newbie]
Thanks
Jack
Advertisement
A simple way to model a state machine is an enumeration and a switch.
Hi rip-off, Thank you for your response. Let me give you a bit of details and see I or we can come up with some ideas. The NPCs I am running have several states IDLE, PATHFINDING, PICKING, SEARCHING, the current coding looks like this switch(current_state) { case IDLE: switch (sub_state) { case GOODS_ARRIVE: return PATHFINDING; //..// case PATHFINDING: switch (sub_state) { case OPERATOR_ARRIVE_ON_SITE: return ATTACHING; case OPERATOR_LEAVE_SITE: return DETACHING; } } Am I on the right track, or there is improvement to it I can make. Thanks Jack
Hi rip-off,
Thank you for your response. Let me give you a bit of details and see I or we can come up with some ideas.
The NPCs I am running have several states IDLE, PATHFINDING, PICKING, SEARCHING, the current coding looks like this

switch(current_state)
{
case IDLE:
switch (sub_state)
{
case GOODS_ARRIVE:
return PATHFINDING;
//..//
case PATHFINDING:
switch (sub_state)
{
case OPERATOR_ARRIVE_ON_SITE:
return ATTACHING;
case OPERATOR_LEAVE_SITE:
return DETACHING;
}
}

Am I on the right track, or there is improvement to it I can make.
Thanks
Jack

Am I on the right track, or there is improvement to it I can make.


Don't hard code it, create a data driven system, so you can write state machine data (states, actions/transitions, conditions) in a data file, so you can edit the state machine without code rebuilding.
and if it"s a state machine that update often, you can change remove the switch and uses funtion pointer instead :


typedef void (Machine::*STATE)(float); ///< this is a state for state machine
#define VS_IDLE &Machine::stateIdle
...
STATE mState; ///< this is the current state, be sure it's never null

and in you source :

void update(float iDeltaTime){
(this->*mState)(iDeltaTime);
}
Good ideas, thank you

This topic is closed to new replies.

Advertisement