How to rotate slowly towards the mouse?

I am doing some stuff in unity, and am trying to get an object to rotate slowly towards the mouse. Here is the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
  
  public class Rotate : MonoBehaviour
  {
      void Start()
      {
          
      }
  
      void FixedUpdate()
      {
          Vector3 mousePos = Input.mousePosition;
          mousePos.z = 0;
          Vector3 objectPos = Camera.main.WorldToScreenPoint(transform.position);
          mousePos.x = mousePos.x - objectPos.x;
          mousePos.y = mousePos.y - objectPos.y;
          float angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
          angle -= 90;
          transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
      }
}

@Richard_Ingalls
You can use Quaternion LERP to slowly rotate an object. Here is a simple example of how to use LERP in Unity

The code you provided looks correct and should rotate the object towards the mouse position. If you are not seeing the object rotate as expected, it could be due to a few reasons:

  • The FixedUpdate function is not being called at regular intervals, which could cause the rotation to be calculated incorrectly. Try using the Update function instead to see if that fixes the issue.

  • The transform.rotation property is being overwritten elsewhere in your code. Try using the transform.localRotation property instead, which will only affect the local rotation of the object, not any of its parent objects.

  • The object is not visible on the screen, so the rotation calculation is not being performed. Make sure the object is visible and within the bounds of the camera‚Äôs view.