views:

7083

answers:

3

Suppose I have a line segment going from (x1,y1) to (x2,y2). How do I calculate the normal vector perpendicular to the line?

I can find lots of stuff about doing this for planes in 3D, but no 2D stuff.

Please go easy on the maths (links to worked examples, diagrams or algorithms are welcome), I'm a programmer more than I'm a mathematician ;)

+2  A: 
m1 = (y2 - y1) / (x2 - x1)

if perpendicular two lines:

m1*m2 = -1

then

m2 = -1 / m1 //if (m1 == 0, then your line should have an equation like x = b)

y = m2*x + b //b is offset of new perpendicular line..

b is something if you want to pass it from a point you defined

ufukgun
+17  A: 

if we define dx=x2-x1 and dy=y2-y1, then the normals are (-dy, dx) and (dy, -dx).

Note that no division is required, and so you're not risking dividing by zero.

Oren Trutner
It's quite subtle and took me a while to realise normal.x = -dy and normal.y = dx. I had them the other way around because it looked like a typo assigning the x part to the y value...
Piku
+5  A: 

Another way to think of it is to calculate the unit vector for a given direction and then apply a 90 degree counterclockwise rotation to get the normal vector.

The matrix representation of the general 2D transformation looks like this:

x' = x cos(t) - y sin(t)
y' = x sin(t) + y cos(t)

where (x,y) are the components of the original vector and (x', y') are the transformed components.

If t = 90 degrees, then cos(90) = 0 and sin(90) = 1. Substituting and multiplying it out gives:

x' = -y
y' = +x

Same result as given earlier, but with a little more explanation as to where it comes from.

duffymo