PointAtMouse() : Point an object at the mouse pointer

This is a method to point an object at the mouse pointer. If you cal this method from Update the object will rotate to follow the mouse as it moves. As with all these solutions, there is no right or wrong way. This is just one that I found to work well in most cases.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    /// <summary>
    /// Method to point this object at the mouse position
    /// </summary>
    void PointAtMouse()
    {
        Vector3 mousePos = Input.mousePosition;
        mousePos.z = 0f;
 
        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) - 90f;
        transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle ));
    }