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.
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.
//"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