Turret lookrotation problem

This is a problem I’ve had a for a few weeks now that’s making me pull my hair out. I’ve scoured the web for a solution and nothing seems to work.

Basically, I have a turret mounted to a spaceship. The turret is made of two parts: the base and the barrel. The barrel is parented to the base, and the base is parented to the ship. The problem is that when the ship rotates in the direction of the turret’s target, the turret loses its rotation relative to the ship. Screenshot here.

This is the code I’m using:

targetVector = target.position - transform.position;
transform.rotation = Quaternion.LookRotation(targetVector,hardpointPosition.transform.up);

Any help would be much appreciated.

When answering a turret question awhile back where the turret was fixed on the XZ plane, I gave some thought about how it might be done on a moving object. Let’s assume that the turret is rotating around the local ‘Y’ of the turret object. The way to get it to rotate correctly is to:

  1. Project the target point onto a plane parallel to the local XZ plane of the object.
  2. Use the transform.up as the up vector in your LookRotation() (which you do with your code now).

Planes are typically constructed using a normal and a point. The normal will be transform.up of the turret. The point will be transform.position of the turret. You can look at the code in this library to see how to project a point onto the plane:

http://wiki.unity3d.com/index.php/3d_Math_functions

It can also be done a bit less efficiently using Unity’s mathematical Plane class.

The point you project on the plane will become the target point you use to construct the vector used in LookRotation().

If you get stuck, I can work up a bit of sample source (when I have a bit more time).