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

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

perpendicular lines

  • \$\begingroup\$ 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? \$\endgroup\$ – PeteUK Jun 12 '17 at 11:04
  • \$\begingroup\$ They are the other way around. PerpendicularCounterClockwise should return (10,5) and PerpendicularClockwise should return (-10,-5). \$\endgroup\$ – opetroch May 14 '18 at 11:59
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ – 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 }.

  • 12
    \$\begingroup\$ 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. \$\endgroup\$ – TravisG Feb 8 '14 at 20:11
  • 1
    \$\begingroup\$ You should negate the y axis to have a CCW rotation by traditional convention. \$\endgroup\$ – RandyGaul Feb 8 '14 at 20:20
  • \$\begingroup\$ @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. \$\endgroup\$ – PeteUK Jun 12 '17 at 10:44

If (ax, ay), then a-perp obtained by a counterclockwise rotation by 90 degrees, i.e., (-ay, ax)

See this link :)


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.