unity rotate towards mouse object 2d code example

Example 1: how to make an object point towards the mouse in unity

//Inside your update loop, add the following code:

//First, get the mouse position
Vector2 mousePosition = new Vector2 ( 
  Input.GetAxis("MouseX"), 
  Input.GetAxis("MouseY")
);
//Then, use unity's built-in lookAt function to do all the math for you:
transform.LookAt(mousePosition);

Example 2: Point to mouse 2D Unity

Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
        difference.Normalize();
        float rotation_z = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0f, 0f, rotation_z + offset);

Example 3: how to make a object rotate towards a position in 2d unity

Vector3 targ = staticCompassTarget.transform.position;
 targ.z = 0f; 
 Vector3 objectPos = transform.position;  
 targ.x = targ.x - objectPos.x;  
 targ.y = targ.y - objectPos.y;      
 float angle = Mathf.Atan2(targ.y, targ.x) * Mathf.Rad2Deg;   
 transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));