41
\$\begingroup\$

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?

\$\endgroup\$
0

3 Answers 3

35
\$\begingroup\$

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

perpendicular lines

\$\endgroup\$
3
  • \$\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, 2017 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, 2018 at 11:59
  • 4
    \$\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\$ May 14, 2018 at 12:34
55
\$\begingroup\$

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 }.

\$\endgroup\$
3
  • 14
    \$\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, 2014 at 20:11
  • 1
    \$\begingroup\$ You should negate the y axis to have a CCW rotation by traditional convention. \$\endgroup\$
    – RandyGaul
    Feb 8, 2014 at 20:20
  • 1
    \$\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, 2017 at 10:44
8
\$\begingroup\$

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

See this link :)

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .