unity look at mouse code example

Example 1: unity get mouse position

Vector3 worldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

Example 2: unity player look at mouse

private void Update()
    {
        Vector3 mousePos = Input.mousePosition;
        mousePos.z = 5.23f;

        Vector3 objectPos = UnityEngine.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;
        transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle - 90));
    }

Example 3: how to look around with mouse in unity

public class CameraController : MonoBehaviour //The script should be on the camera or on the player if it is a sphere
{
	
  	Vector2 rotation = Vector2.zero;
	public float speed = 3; //the sensibility

	void Update () 
    {
		rotation.y += Input.GetAxis("Mouse X");
		rotation.x += -Input.GetAxis("Mouse Y");
		transform.eulerAngles = (Vector2)rotation * speed;
	}
}

Example 4: unity 2d looka tt mouse

void Update() {
     Vector3 dir = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
     float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
     transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);