How to rotate a Vector2 direction?
How do I rotate a Vector2 direction by 90 degrees? I have a direction (Vector2(0, 1)) and I need to rotate it by 90 degrees. This would mean it would be Vector2(1, 0) but the problem is I need it to randomly select either -90 degrees or 90 degrees (nothing in between) and also I need it to be able to have the original direction (before rotation) as any amount of 90 degree turns.
Answer by Dave-Carlile · Sep 15, 2015 at 05:55 PM
I've always thought that Unity should have these sorts of things somewhere but I've never been able to find them (other than setting up a Matrix which seems like overkill for this). I don't have Unity in front of me, but this should do the trick for getting a Vector2 from an angle...
public Vector2 Vector2FromAngle(float a)
{
a *= Mathf.Deg2Rad;
return new Vector2(Mathf.Cos(a), Mathf.Sin(a));
}
You can pass in any angle (in degrees) and it will give you the appropriate vector pointing in that direction. So now you just need to keep track of the angle and modify it based on user input. Pseudo code would be something like...
float angle = 0;
void Update()
{
if (turn left key pressed)
angle += 90;
else if (turn right key pressed)
angle -= 90;
Vector2 v = Vector2FromAngle(angle);
}
If Unity has this built in somewhere, someone let me know :)