Skip to main content
GameDev.net gamedev.net
🔒 Locked

How to design a state machine?

Started by lucky6969b Nov 15, 2011 at 1:24 PM 4 replies 1.3k views
Original Post
lucky6969b
lucky6969b
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
rip-off
rip-off
A simple way to model a state machine is an enumeration and a switch.
lucky6969b
lucky6969b
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
zfvesoljc
zfvesoljc

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.
mcmuzzle
mcmuzzle
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);
}
lucky6969b
lucky6969b
Good ideas, thank you

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.