# LookRotation() make X axis face the target instead of Z

I use LookRotation() in order for an object to look at another, but since I'm using 2D I would like to make the axis looking/facing the target to be X instead of Z. I have the code below currently:

Vector3 dif = targetPos - obj.position;
Quaternion angle= Quaternion.LookRotation(dif, obj.up);
obj.rotation = Quaternion.Lerp(obj.localRotation, angle, Time.deltaTime);


Now->

What I'm trying to achieve->

Thanks!

• One quick aside: the way you're using Lerp above will give different results at different framerates. If you want to rotate at a constant angular velocity, use Quaternion.RotateTowards. Or, if you want an exponential ease-out behaviour similar to what you have now but consistent at different framerates, set your interpolant to Mathf.Pow(fractionRemainingAfterOneSecond, Time.deltaTime). Also, be careful intermixing localRotation and rotation - this can give unexpected behaviour when the object has a rotated parent. – DMGregory Apr 3 '17 at 17:07

I've answered a few flavours of this before.

The basic idea is to chain together two rotations: one that takes the axes you want to align and points them along z+ and y+ respectively, and then the standard LookRotation to take z+ and y+ to the desired destination axes.

For a straight 3D analogue of LookRotation that positions the x+ axis instead of z+, but still treats y+ the same way as ordinary LookRotation:

Quaternion XLookRotation(Vector3 right, Vector3 up = Default(Vector3))
{
if(up == Default(Vector3))
up = Vector3.up;

Quaternion rightToForward = Quaternion.Euler(0f, -90f, 0f);
Quaternion forwardToTarget = Quaternion.LookRotation(right, up);

return forwardToTarget * rightToForward;
}


Or, to keep an object locked in 2D with z+ forward, as in the second link above:

Quaternion XLookRotation2D(Vector3 right)
{
Quaternion rightToUp = Quaternion.Euler(0f, 0f, 90f);
Quaternion upToTarget = Quaternion.LookRotation(Vector3.forward, right);

return upToTarget * rightToUp;
}

• Thanks, I have a few questions, Will this function return the final rotation? What rotation do I put into the 'right' variable (Vector3)? – Vadim Tatarnikov Apr 3 '17 at 16:40
• Yes. Just like the original LookRotation, this takes one or two direction vectors you want to point your object toward (so "right" is the direction you want the object's local x+ axis to point along), and returns a quaternion representing an orientation with the axes pointed the way you requested. – DMGregory Apr 3 '17 at 16:44
• Re: XLookRotation Thanks a million, I was looking all over for how to do this and getting nowhere. btw Default(Vector3) doesn't seem to be valid, so I used Vector3.zero. – dt192 Feb 19 at 16:46