# Calculating angle between two vectors to steer towards a target

I have been trying to implement a path following steering behaviour for AI in a 2D racing game.

I have two vectors: futurePosition represents the predicted future position given the car's current heading. futurePathPosition represents the nearest point on the path to the predicted future position.

By working out the relative orientation of these two vectors, I should be able to determine whether the car needs to turn left or right in order to head towards the centre of the path.

I've tried different calculations, but I just can't get it to follow the path consistently. Occasionally the car will turn the wrong way and get "stuck".

I am currently determining the angle using the cross product, as suggested here.

var a = Vector2D.normalize(this.futurePathPosition);
var b = Vector2D.normalize(this.futurePosition);
var d = Vector2D.cross(a, b);

if(this.futureDistanceFromPath > this.trackRadius) {
if(d > 0)
this.steerLeft();
else if(d < 0)
this.steerRight();
else if(d == 0)
this.steerAngle = 0;
}
else
this.steerAngle = 0;


Any tips on what might be causing this bug would be appreciated.

Also, I wondered if axis orientation affects how calculations are performed on vectors? In canvas the y axis faces "south", but in the vector tutorials I have read I haven't seen axis orientation mentioned.

## 2 Answers

Shouldn't you be performing the vector crossing on the heading vectors, rather than on the positions? Positions could be any set of values.

I think the two vectors should be

// direction from current to intended
a = Vector2D.Normalize(this.futurePathPosition - this.position);
// direction from current to next point along heading
b = Vector2D.Normalize(this.futurePosition - this.position);


My signs might be off. Switch left/right as required.

• Thank you! As my first time working with vectors, I'm sometimes muddling/forgetting when I'm using points and when vectors. This fixed it. – Ivan Aug 19 '12 at 7:55

Cross products don't make much sense 2d. Or at least, they don't produce useful results (2d vectors are always on the xy plane, right, so if you cross any two, the result always contains only a z component).

To determine the angle between two unit vectors, you can take the arc-cosine of the dot-product of them. The dot-product gives you a scalar which is the cosine of the angle * the product of their magnitude.

To work out whether to steer left or right, you can use a dot-product between the desired azimuth, and a vector pointing "right" from your vehicle. If the result is >0, then you need to steer right, otherwise left.

The "right" vector can be obtained by trivially rotating the "forward" vector by 90 degrees (multiply it by a matrix of (0,1),(-1,0) )