Spacesim AI pilot, vector3.cross issues

Hi there, I am trying to get some space sim AI piloting off the ground. I am using vector3.cross to help determine which way the AI pilot needs to turn to face a target, and have ran into problems. Here is the code:

void TurnToTarget () {

		Vector3 neededRotation = aiEngine.destination - transform.position;

		if (Vector3.Angle(transform.forward, neededRotation) > 1) {

			Debug.Log (Vector3.Angle(transform.forward, neededRotation));

			facingTarget = false;

			Vector3 cross = Vector3.Cross (transform.forward, neededRotation);

			Debug.Log (cross);

			Roll ();

			if (cross.x != 0) {

				Pitch (cross.x);
			}

			if (cross.y != 0) {
				
				Yaw (cross.y);
			}

		} else {

			facingTarget = true;
		}
	}

Roll () doesn’t do anything yet, but pitch and yaw take the x and y components of vector3.cross respectively, and use the sign of the x or y to decide which direction to turn in. This nearly works, except the AI sometimes gets confused and flies directly away from the target instead of directly towards it. I thought I could fix this by throwing in the if (Vector3.Angle(transform.forward, neededRotation) > 1) buisness, but it doesn’t totally help.

I’m suspecting the reason for this is that when the ship’s rotation changes, the position of the positive and negative .cross componenets can change meaning the ship might try to turn left instead of right, or up instead of down. I don’t yet know if this is correct, but if it is, what can I do to stop this? (Aside from keep my ship perfectly level at all times!). Is there a way to make the vectors more localised? Or is there a quaternion equivilent that might work better?

Cheers in advance for your help,

Pete

Quaternions all the way. Had very bad experiences with Vector3 myself.

Vector3 neededRotation = aiEngine.destination - transform.position;
Quaternion neededRotationQ = Quaternion.LookRotation(neededRotation);
transform.rotation = neededRotationQ;

Imo this looks a bit edgy with no interpolation, so you might use:

//instead of transform.rotation = neededRotationQ;
float interpolationSpeed = 10.0f;
transform.rotation = Quaternion.Slerp(transform.rotation, neededRotationQ, Time.deltaTime * interpolationSpeed);

Best tip for quaternion rotations for your future:

A and B are quaternions:
A * B = Applying local rotation B on A = Applying global rotation A on B