I'm making a top down game where the player moves forwards towards the position of the mouse cursor. As part of the player's movement code, I need to determine a vector that is perpendicular to the player's current facing vector (to implement strafing behavior).
How can I compute the perpendicular vector of a given 2D vector?
Answer
I always forget how to do this when I need it so I wrote a couple of extension methods.
public static Vector2 PerpendicularClockwise(this Vector2 vector2)
{
return new Vector2(vector2.Y, -vector2.X);
}
public static Vector2 PerpendicularCounterClockwise(this Vector2 vector2)
{
return new Vector2(-vector2.Y, vector2.X);
}
And a unit test
[Test]
public void Vector2_Perpendicular_Test()
{
var a = new Vector2(5, -10);
var b = a.PerpendicularClockwise();
var c = a.PerpendicularCounterClockwise();
Assert.AreEqual(new Vector2(-10, -5), b);
Assert.AreEqual(new Vector2(10, 5), c);
}
No comments:
Post a Comment