I’ve followed 3DBuzz’s XNA AI tutorial and it uses vectors to calculate object directions. I’m having trouble understand a simple piece of code that moves an object in a given direction (The 3DBuzz videos don’t really dig deep into the vector math).
A bit of background
The AI system uses Actor classes which you can assign Behaviors. Behaviors have a set weight property defining how much of the behavior is taken into account when working with multiple behaviors. Below is a behavior for moving an object in a constant direction. This is the update method, being continuously called.
public override void Update(Actor actor)
{
actor.Direction += this.direction * this.Weight;
}
The thing I don’t understand is, why does my object move in a constant direction while the Actor’s Direction variable is incremented with that direction each frame?
Initially I thought it was because the Direction vector is normalized on each update in the Actor class, but when logging my direction before and after the normalization, they’re both different. This is my output (Trace.WriteLine):
DIR: {X:0.7071068 Y:0.7071068}
NOR: {X:0.7071068 Y:0.7071068}
DIR: {X:2 Y:2.537759E-27}
NOR: {X:1 Y:1.268879E-27}
DIR: {X:0.7071068 Y:0.7071068}
NOR: {X:0.7071068 Y:0.7071068}
DIR: {X:2 Y:1.268879E-27}
NOR: {X:1 Y:6.344397E-28}
DIR: {X:0.7071068 Y:0.7071068}
NOR: {X:0.7071068 Y:0.7071068}
DIR: {X:2 Y:6.344397E-28}
NOR: {X:1 Y:3.172199E-28}
DIR: {X:0.7071068 Y:0.7071068}
NOR: {X:0.7071068 Y:0.7071068}
DIR: {X:2 Y:3.172199E-28}
NOR: {X:1 Y:1.586099E-28}
DIR: {X:0.7071068 Y:0.7071068}
NOR: {X:0.7071068 Y:0.7071068}
DIR: {X:2 Y:1.586099E-28}
NOR: {X:1 Y:7.930497E-29}
DIR: {X:0.7071068 Y:0.7071068}
NOR: {X:0.7071068 Y:0.7071068}
And the code to get this output (in Actor.cs):
Trace.WriteLine("DIR: " + this.Direction);
if (this.Direction.Length() > 0f)
this.Direction.Normalize();
Trace.WriteLine("NOR: " + this.Direction);
if(IsMoving)
this.Position += this.Direction * this.Speed;
I don’t understand why I’m moving in the same direction while my Direction vector is different each time. Can anyone explain this to me?
As you can see, you are adding vectors and normalizing, and you are aproximating to the vector you are adding…. here the effect is magnified by the module of the behaviour vector direction… with a smaller vector it will takes more cycles to aproximate it.