Rotate Cube Depending On Where The Cursor Is
Hello, I am making a top down perspective game I want the player (in this case a cube) to rotate around like a compass North, West,East,South but also having the ability to be facing NorthWest and SouthEast and everywhere in between. Can anyone throw me in the right direction with a script tutorial?
Answer by Magius96 · Mar 07, 2016 at 04:26 PM
If this were a 3d game, I'd say transform.LookAt() but that doesn't exactly work correctly for 2D games. Instead I use this method:
public static void LookAt2D(ref GameObject obj, Transform target)
{
float angle = 0;
Vector3 relative = obj.transform.InverseTransformPoint(target.position);
angle = Mathf.Atan2(relative.x, relative.y) * Mathf.Rad2Deg;
obj.transform.Rotate(0, 0, -angle);
}
This rotates the object on the Z plane to look at the target.
Out of total curiosity, why do you pass the game object by ref?
It allows me to make changes to the game object without having to return it. To be honest, I have this method in my code as an extension method so I don't have to pass it by ref. To change it to an extension method, make sure you put it into a static class an change "ref" to "this".
Your answer
Follow this Question
Related Questions
X-Axis rotation quirk 0 Answers
Rotate player with mouse. 0 Answers
Rotate OBJECT to face mouse cursor for x/z based top down shooter 3 Answers