I have a flight simulator / jet fighter game. I have other airplanes (enemy targets) flying around in the world. I want to shoot a guided missile at the target. My original approach for this works most of the time, but sometimes fails.
What I have done is found my missile's heading vector, and the vector between the missile and the target. I take the cross product of the 2 vectors to get my rotation axis vector. The angle of rotation is found by arccosine of the dot product of the cross product of my missile & target vectors. Since I do not want the missile to turn directly at the target immediately, I limit the rotation to 2 degrees. After rotating, I move the missile along its forward vector, by its speed.
To explain the failure in this, let me give in an example. The game starts & out in front of my airplane is the target. For this example both objects are flying forward. If I fire the missile, it goes straight for the target and hits.
However, if I roll my airplane over (upside down) the missile seems to turn the wrong direction. It will often make a big loop and eventually find the target and destroy it. It seems that the rotation angle should be negative in this case, but I don't know how to determine if I need to do so.
Here is some basic code to demonstrate:
[source lang="java"]Vector3D targvec = new Vector3D(targetmatrix[12], targetmatrix[13], targetmatrix[14]);
Vector3D R1pos = new Vector3D(R1Matrix[12], R1Matrix[13], R1Matrix[14]);
Vector3D R1head = new Vector3D(R1Matrix[8], R1Matrix[9], R1Matrix[10]);
Vector3D newtargvec = targvec.subtract(R1pos);
newtargvec = newtargvec.normalize();
R1head = R1head.normalize();
float angle = R1head.angleBetween(newtargvec); // acos(R1head.dotProduct(newtargvec)
Vector3D rotaxis = R1head.crossProduct(newvec);
rotaxis.normalize();
if (angle > 2){
angle = 2;
Matrix.rotateM(R1Matrix, 0, (float) angle, rotaxis.getX(), rotaxis.getY(), rotaxis.getZ());
setMoveForwardMatrix(tempMatrix, -(movedist),R1Matrix[8], R1Matrix[9], R1Matrix[10]);
Matrix.multiplyMM(R1Matrix, 0, tempMatrix, 0, R1Matrix, 0);
[/source]