I need to apply rotation to an object, based on the mouse movement around it to a z-axis only.

Let's take this picture:

enter image description here

  • Violet - current mouse position
  • Blue - mouse movement
  • Red - the object to be rotated

I use this script and it works fine:

mousePos = Input.mousePosition;
screenPos = Camera.main.ScreenToWorldPoint(Vector3(mousePos.x, mousePos.y, 
transform.position.z - Camera.main.transform.position.z));

transform.rotation.eulerAngles.z = Mathf.Atan2((screenPos.y - transform.position.y), (screenPos.x - transform.position.x)) * Mathf.Rad2Deg;

but... it work's in real-time which I don't want, so I need to interpolate it. I used Quaternion.Lerp/Slerp and I got a strange result.

When I move the mouse too fast (rotate it around the cube) it lerps to mouse's new position (which is ok) but it changes the rotation direction when the angle changes from -180 to 180 or 180 to -180.

It's because of Quaternion math probably, to be precise - Quaternion decides to switch the rotation direction, because it found a shorter path.

The question

How do I smoothly (with lerp) rotate the object (on a z-axis) to look at the mouse position so it doesn't make the above glitch when lerping?

  • \$\begingroup\$ Have you tried Quaternion.RotateTowards ? \$\endgroup\$ – DMGregory Sep 21 '17 at 11:01
  • \$\begingroup\$ I didn't. Could you make an example Greg? \$\endgroup\$ – Jacob Sep 21 '17 at 12:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.