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.
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 ![]()
Unity does have a couple useful functions with Vector2s and rotations and such (like vector2.angle or whatever ← this function finds the angle between two vectors), but really quaternions are the magical power that can take you very far with rotations!
You can use a Quaternion function to “create a rotation” and then you can apply that rotation to a vector or combine it with another rotation, it’s really cool. Just multiply the vector and the quaternion and make sure your quaternion is on the left ![]()
If you’re still struggling to understand or curious for more i suggest you look into quaternions more; they’re really quat cool ![]()
Vector2 funnyVector = Random.insideUnitCircle; //or whatever your vector is
float angle = Random.value > 0.5f ? 90 : -90;
Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward); //create a rotation of angle degrees around the forward (z) axis
Vector2 rotatedVector = rotation * funnyVector; //just multiply by your quaternion to apply the rotation to a vector. Make sure quaternion is on the left!!!
//once more just for fun VVV
Vector2 rotVector = Quaternion.AngleAxis(90, Vector3.forward) * new Vector2(32, 10);