Monday, March 4, 2019

linear algebra - 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?



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


perpendicular lines


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...