Rotate to align with 2D vector

I googled and searched here in the forums and find a few similar questions but I couldn’t get any of the answers to work properly, my problem is probably very simple.

I’m constructing a 2D demo where I need to rotate my object so it aligns with a vector.

Like this image, my object looks along positive Y and I need to rotate it around Z axis until it looks along the blue vector. Camera sits “above” the object (looks along positive Z).

I tried using transform.LookAt with the new vector as parameter, but cannot get it to work properly. I also tried Quaternion.LookRotation without success.

Edit: I also tried calculating the angle between the two vectors and rotating by result along z, but this resulted in having to do various controls and calculations to know if I should rotate clockwise or counter clockwise. So Id rather use the vector directly if possible.

Any help appreciated!

1193245--47117--$1f94dc72ea5674a5d9af023bfd3a2b29821d3c2f.jpg

1193245--47116--$30ktyd2.png

Why not just take the vector, add it to the current pos, and then “LookAt” the new pos?

Thanks for your reply, I tried using LookAt as you suggested, but the 2D sprite rotated on other axies than Z (it flipped). I ended up using:

transform.rotation = Quaternion.FromToRotation(transform.position, newVector);

with newVector.z zeroed out. This works well, but I cannot wrap my head around why I could not use transform.LookAt. I tried with several different up vectors.

With a static object the Quaternion solution above seemed to work but as I add translation to my object the rotation start to drift. I can also tell by looking at my rotation angles in Unity that the rotation is not strict around the Z axis.

Can anyone give me some hints on how to rotate on Z axis only to face a specific point?

After reading up on how to use Quaternions I ended up using Quaternion.SetFromToRotation, and then setting its eulerAngle X and Y to zero beforing assigning it as rotation. Works great.

var rot = Quaternion.SetFromToRotation(fromVector, targetVector).eulerAngles;
rot.x = 0f;
rot.y = 0f;

transform.rotation = Quaternion.Euler(rot);
1 Like

transform.rotation = Quaternion.LookRotation(targetVector, Vector3.forward);

Avoid Eulers where you can, they can stab you in your back :wink:

C#

//"target.position - from.position" is the direction.
//I always get confused which order to put them in
//so it may be "from.position - target.position"
Quaternion rotation = Quaternion.LookRotation(target.position - from.position);

Yes, but in this case you also have to define the second parameter, the up vector that is not the default Y, but Z. Thats why you have to add Vector.forward