How can I find the perpendicular to a 2D vector?

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?

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);
}


• If you have a vector (5,-10) then it'll be in quadrant 4, right? If you then rotate it clockwise, won't it be in quadrant 3 i.e. both components negative? Have you got your functions mixed up? – PeteUK Jun 12 '17 at 11:04
• They are the other way around. PerpendicularCounterClockwise should return (10,5) and PerpendicularClockwise should return (-10,-5). – opetroch May 14 '18 at 11:59
• Oh my.. this was wrong for 3 years. My apologies to anyone who used it. I've now fixed the answer and drew a diagram to prove that it makes sense this time. Thanks to @opetroch and PeteUK for pointing this out. Sorry it took so long to correct it. – craftworkgames May 14 '18 at 12:34

To get the 2D vector perpendicular to another 2D vector simply swap the X and Y components, negating the new Y component. So { x, y } becomes { y, -x }.

• Note that there are two possibilities, and this one will get you the left-hand perpendicular vector. (-y|x) is the right-hand side vector. – TravisG Feb 8 '14 at 20:11
• You should negate the y axis to have a CCW rotation by traditional convention. – RandyGaul Feb 8 '14 at 20:20
• @TravisG I think you've got the left and right mixed up? (-y, x) is the left hand perpendicular vector and (y, -x) is the RHS from my calculations. – PeteUK Jun 12 '17 at 10:44

If , then a-perp obtained by a counterclockwise rotation by 90 degrees, i.e.,