What you need to begin is a variable that keeps track of what state the AI is currently in. I prefer an Enum since you can name each state with a unique title, but you could also simply use an Int so long as you can keep track of which state is which number.
Next you have to set up a hierarchy or tree that your AI will check against to tell it what state it should be in. This hierarchy is one way to help define how 'smart' your AI is and how complex its actions are. For ease of an example lets say we're building an AI for capture the flag.
Something like this. Or something much, much bigger. Your choice. |
And that's it. State machine AI's are pretty simple and fun to make (at least I think so).
---
Now for some example code!
void AIUpdate()
{
CurrentAIState = CheckDemStates();
switch(CurrentAIState)
{
case AIState.Attacker:
//Seek out the flag
break;
case AIState.Defender:
//Cover our flag
break;
case AIState.Rescuer:
//ZOMG, get our flag back!
break;
}
}
AIState CheckDemStates()
{
if(//they got the flag)
{
if(//Rescuers > X)
{
return AIState.Attacker;
}
else
{
if(//Other teammates are closer)
{
return AIState.Attacker;
}
else
{
return AIState.Rescuer;
}
}
}
else
{
if(//Defenders > X)
{
return AIState.Attacker;
}
else
{
return AIState.Defender;
}
}
}
{
CurrentAIState = CheckDemStates();
switch(CurrentAIState)
{
case AIState.Attacker:
//Seek out the flag
break;
case AIState.Defender:
//Cover our flag
break;
case AIState.Rescuer:
//ZOMG, get our flag back!
break;
}
}
AIState CheckDemStates()
{
if(//they got the flag)
{
if(//Rescuers > X)
{
return AIState.Attacker;
}
else
{
if(//Other teammates are closer)
{
return AIState.Attacker;
}
else
{
return AIState.Rescuer;
}
}
}
else
{
if(//Defenders > X)
{
return AIState.Attacker;
}
else
{
return AIState.Defender;
}
}
}
No comments:
Post a Comment