Object won't rotate along a single axis?

I have a turret that I am trying to rotate only along the Y axis until it is facing a target. Now, I cannot for the life of me get it to only rotate along the Y using the transform.LookAt function. It should only be rotating across one axis, but all three are changing.

Here is my code I am using and the results:

    Vector3 lookPos = target.position - transform.position;
    lookPos.y = 0;
    Quaternion rotation = Quaternion.LookRotation(lookPos);
    transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime); damping);

Before and after the target(the cube) is assigned:

Before: transform.rotation is

(270,0,0)

After: transform.rotation is

(-.00046, 96.70226, -0.00051)

21948-fadsdfsafdsa.png

21949-fsafaa.png

You might want to try using Quaternion.LookRotation(lookPos, transform.up); I'm away from my unity computer right now but I have a feeling you can use the second optional parameter of LookRotation to do this for you! Scribe

1 Answer

1

If you just want to rotate on one axis I find it simpler and clearer to manipulate the eulerAngles of the current rotation, something like this may work for you…

Vector3 lookPos = target.position - transform.position;
Quaternion rotation = Quaternion.LookRotation(lookPos);    

Vector3 targetAngles = rotation.eulerAngles;
Vector3 currentAngles = transform.rotation.eulerAngles;

currentAngles.y = Mathf.LerpAngle(currentAngles.y,targetAngles.y,Time.deltaTime);
transform.rotation.eulerAngles = currentAngles;

You may still encounter problems when/if the parent object rotates though, you may want to think about limiting the local rotation instead, this makes much more sense for a turret.

Hope this helps.

Hmm, interesting. I've never worked with Euler angles before so I'll try and give it a go.

I agree with Phles. Euler angles are a cleaner way to do this because the turret only has one axis. NOTE: If your turret axis is not always aligned with the world Y axis, then you will have to specify the local up axis like this: Quaternion rotation = Quaternion.LookRotation(lookPos, transform.up);