Rotate object to face another while retaining its orientation towards the camera.

A rather simple issue that has given me headaches recently. In the context of a 2.5D sidescrolling game, i have a hypothetical turret model that looks different on either side, which i want to look at the player at all times. Movement happens along the X global axis.

http://puu.sh/d8CJh.jpg

Assuming the hypothetical player is the blue cube, tracking works fine when he is at the left of the turret.

alt text

Whenever he goes to the right though, the turret’s orientation changes and it suddenly turns around to have its other side face the camera.

alt text

This is of course unwanted behaviour. I have temporarily solved it by detecting whether the rotation faces towards the global X axis and adjusting Y and Z rotation values accordingly, but i’d like to see if there is a more elegant solution. (And besides that, i can only assume there will be issues with interpolation)

Here is the simple test code that i’m using, without the dot product check to see if the rotation is facing towards the global X axis and the subsequent rotation changes. It is essentially identical to transform.LookAt().

targetRotation=Quaternion.LookRotation(playerObject.position-rotationObject.position);
rotationObject.rotation=targetRotation;

Many thanks in advance.

Provide the LookRotation with the up axis you want the object to use/rotate around.
In your situation that would be towards the camera or negative on the global z (depending on your setup). This way the object will not flip, but always set the up direction towards the camera and the forward direction towards the target object.

Example:
//Negative Vector3.forward is the global negative z direction.
targetRotation=Quaternion.LookRotation(playerObject.position-rotationObject.position, -Vector3.forward);