2009
02-17

# XNA Series – Modular AI

In our last installment, we created a very specific AI interaction. We moved toward another object and then as we approached, we slowed down. In today’s post we will look at breaking that out into more granular, reusable steps.

First Thing we need to do is to turn towards our target. Which may be an object, an agent or just some arbitrary location, like a waypoint on a track. Then no matter why we need to turn, we have a way to do a targeted turn. For the sake of flexibility, we will add a turnSpeed to the method so that depending on the call we can determine how fast we will turn.

`public void TurnTowards(Vector2D target, float turnSpeed){           Vector2 difference = target-position;           float objectRotation = (float)Math.Atan2(difference.Y, difference.X);           float deltaRotation = MathHelper.WrapAngle(objectRotation - rotation);           rotation += MathHelper.Clamp(deltaRotation, -turnSpeed, turnSpeed);}`

and then we want to be able to move forward. So we create a move forward method.

`public void MoveForward(float speed)       {           position.X += (float)Math.Cos(rotation)*speed;           position.Y += (float)Math.Sin(rotation)*speed;       }`

where we determine what to add to our current location by getting a unit circle offset from us based on our rotation and then multiply it by our speed.

Now that we have these 2 behaviors, we can construct a Seek method, where we turn towards our target at our turnspeed and then move towards our target using our speed.

`public void Seek(Vector2 target, float speed, float turnSpeed){    TurnTowards(target, turnSpeed);    Move(speed);}`

So with this in our Update method if we had to GameObjects that implemented this Seek method we could call

`a.Seek(b.position,2f, 0.02f);`

To set our a object seeking b. But like I said, we don’t have to stop there, there are other things we can do with these methods. Check back next time and I’ll talk about how we can make our objects follow a path that we add to by mouse clicking. (Code for this and the next project will be in the next post). 