0

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->

enter image description here

What I'm trying to achieve->

enter image description here

Thanks!

John Smith
  • 1,255
  • 1
  • 20
  • 41
  • 1
    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 03 '17 at 17:07

1 Answers1

4

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)
{
    if(up == default)
      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;

}

DMGregory
  • 134,153
  • 22
  • 242
  • 357
  • Thanks, I have a few questions, Will this function return the final rotation? What rotation do I put into the 'right' variable (Vector3)? – John Smith Apr 03 '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 03 '17 at 16:44
  • For future readers, if you want something almost like this but with different axes, check if this more general answer serves your needs. – DMGregory Mar 14 '23 at 00:16