- Home /
How can I rotate an object towards the mouse in only one axis?
I'm working on a 2d game and I'm trying to get my ship to move by clicking with my mouse. I've gotten the ship to move but I can't get it to rotate to look into that direction. I'm using this code:
float angle = Mathf.Atan2(target.y, target.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
The ship does rotate but it seems like its taking the center of the ship as reference so the front of the ship isn't facing the direction it should. Also for some reason the ship seems to do a random backflip.
Here is what I have so far if it helps you understand the problem.
Answer by Pyrian · Oct 19, 2014 at 08:28 PM
First, you need to take into account your current position. Right now you're just pointing the craft as if you're at the origin - even when you're not.
So, "Mathf.Atan2(target.y, target.x)" needs to be "Mathf.Atan2(target.y - transform.position.y, target.x - transform.position.x)".
You probably also need to add or subtract 90 to/from the resulting angle to point the correct facing.