Rotate Towards Mouse Unity 2D code example
Example 1: 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 2: 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));
Example 3: unity 2d rotate towards direction
private void RotateGameObject(Vector3 target, float RotationSpeed, float offset)
{
Vector3 dir = target - transform.position;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.Euler(new Vector3(0, 0, angle + offset));
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, RotationSpeed * Time.deltaTime);
}