Reputation: 12684
I'm trying to build a boss enemy using a simple state machine for his different behaviours. I'm trying to build an Attacking and Waiting state as it is, but I'm running into some issues.
How can I make the states switch automatically? Ideally, I'd like the boss to be attacking for a specified amount of time, then waiting (at which time he is vulnerable) for another amount of time. But the waiting is the issue I'm running into. Is there a good way to go about this?
EDIT: The State machine I'm writing currently looks like this:
public class BossStateMachine : MonoBehaviour
{
/* TODO: Figure out WAITING for state changes */
private delegate void State(); //create delegate
private State stateMethod; //create holder for delegate
bool canBeAttacked = false;
public int bossHealth = 5; //takes 5 hits
/*
* States:
* Attacking - boss is attacking, is not vulnerable
* Waiting - boss is not attacking, is vulnerable
*/
// Use this for initialization
void Start ()
{
stateMethod = new State(EnterStateAttacking);
}
// Update is called once per frame
void Update ()
{
}
void FixedUpdate()
{
stateMethod();
}
private void EnterStateAttacking()
{
canBeAttacked=false;
stateMethod = new State(Attacking);
stateMethod(); //start in same frame (comment out to delay)
}
private void Attacking()
{
FireBlast(); //method of attack
}
private void EnterStateWaiting()
{
canBeAttacked=true;
stateMethod = new State(Waiting);
stateMethod();
}
private void Waiting()
{
//wait (open to attack from player)
//do laughing or something
}
}
I'd like to have both the Waiting state and the Attacking state enter and exit on their own. Even through the update function, how can I do this?
Upvotes: 0
Views: 4936
Reputation: 65087
In it's simplest form, you could have it switch backwards and forwards between states.. something like this:
private TimeSpan timeToWait = TimeSpan.FromMilliseconds(5000); // 5 seconds
private TimeSpan lastStateCheck;
public void Update(GameTime gameTime) {
if (lastStateCheck + timeToWait < gameTime.TotalGameTime) {
// switch states after 5 seconds..
/* Switch state code here */
lastStateCheck = gameTime.TotalGameTime;
}
}
A more advanced AI would perform a lot more checks, such as whether the player has been seen, or whether it should continue to attack if the player is directly in front of it.
PS: I didn't vote to close (thought I should mention that)
Upvotes: 1