Reputation: 35
I am trying to rotate my 2d object around my mouse. This is the code I have:
void Update()
{
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 direction = mousePosition - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0, 0, angle);
// Debug.Log(angle);
}
My object, which is an arrow, is by default pointing down, so before I start the script I set its z rotation to 90, so it faces right. If I delete the transform.rotation
line, the angle shown will be right, when my cursor is above it says 90, in the left it says 180 etc. So my question is: Why do I need to add 90 degrees to angle to make this actually work? Why doesn't this version work?
Upvotes: 0
Views: 4514
Reputation: 90580
Mathf.Atan2
(Also see Wikipedia - Atan2)
Return value is the angle between the x-axis [=
Vector3.right
] and a 2D vector starting at zero and terminating at (x,y).
It would work as expected if your arrow by default would point to the right but yours is
by default pointing down
you could simply add the offset rotation on top like
transform.rotation = Quaternion.Euler(0, 0, angle + 90);
Alternatively if you need this for multiple objects with different offsets either use a configurable field like
[SerializeField] private float angleOffset;
...
transform.rotation = Quaternion.Euler(0, 0, angle + angleOffset);
Or you could rotate it manually to face correctly to the right before starting the app and store that default offset rotation like
private Quaternion defaultRotation;
private void Awake ()
{
defaultRotation = transform.rotation;
}
and then do
transform.rotation = defaultRotation * Quaternion.Euler(0, 0, angle);
Upvotes: 3