Saturday, April 18, 2015

mathematics - 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.



Answer



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.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...