Following your advice I've created a simple struct that holds the AI behaviour and the period in which it takes place:
public struct BulletState { public AIState state; // AI state for bullet public float period; // Period to remain in that state for public BulletState(AIState state, float period) { this.state = state; this.period = period; } }
A timer class evaluates each period:
class PeriodTimer { float currentTime; float period; /// <summary> /// Returns true after a period of time has passed /// </summary> /// <param name="period">Period of time (ms)</param> public PeriodTimer(float period) { this.period = period; currentTime = 0.0f; } public void Update(GameTime gameTime) { currentTime += (float)gameTime.ElapsedGameTime.TotalMilliseconds; } public bool HasPeriodElapsed { get { return currentTime >= period; } } public float Period { get { return period; } set { period = value; currentTime = 0.0f; } } }
Now I set up the AI as follows:
BulletState[] states = new BulletState[4]; int stateIndex = -1; PeriodTimer stateTimer = new PeriodTimer(0);... states[0] = new BulletState(AIState.Moving, 1000); states[1] = new BulletState(AIState.Waiting, 1000); states[2] = new BulletState(AIState.Moving, 1000); states[3] = new BulletState(AIState.Waiting, 1000);
and then my Update() method now looks like the following:
public override void Update(GameTime gameTime) { // Update the timer stateTimer.Update(gameTime); // Check to see if the period for the current state has elapsed if (stateTimer.HasPeriodElapsed) { stateIndex++; // What should I do if the final state has expired? if (stateIndex >= states.Length) { stateIndex = Math.Min(stateIndex, states.Length - 1); } else { stateTimer.Period = states[stateIndex].period; } } switch (states[stateIndex].state) { case AIState.Moving: { // Move the object Position = Body.Position; Rotation = Body.Rotation; Body.Velocity = direction * speed; break; } case AIState.Waiting: { // Don't move Body.Velocity = Vector2.Zero; break; } } }
Are there any changes you would suggest to this structure?
What would you do in the case of the final state reaching the end of its period?