Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given 2 points how do I draw a line at a right angle to the line formed by the two points?

Tags:

geometry

Idealy I want to supply a sequence of points and have a line drawn at a right angle at every point (starting at the second point).

The direction of each line would alternate, so if I happened to draw a curve cosisting of 6 points, a line of a given lenth would be drawn for each point starting with the second point, i.e 5 additional lines on alternating sides of the curve, a bit like a caterpillar with alternating legs.

(I understand that the lines won't be entirely at right angles to the curve but rather at right angle to the line formed by any two points on the curve).

like image 248
descf Avatar asked Sep 19 '11 11:09

descf


1 Answers

It's a question of vector mathematics. You can calculate the directing vector between two points A and B by subtracting A from B. In 2D and only in 2D the vector right angled to this vector can be obtained by reversing x and y component and taking one component negative. If you negate the new x component you'll make a left turn, by negating y you'll make a right turn. You can then reduce the directing vector to unit size (= of length 1) by dividing each component by the length of the vector (sqrt(xx + yy)). Finally you can stretch the unit vector again by your desired length and have one of the size you want. If you add this vector to either A or B you'll get a point to which you want to draw your line.

Here's a little math help:

These are points A and B expressed as vector.

The directing vector is calculated by a simple subtraction.

The normal vector is given by flipping the directing vector, that is to reverse the components and make one component negative. nl = normal, flipped to the left, nr = normal, flipped to the right

The unit vector of the normal vector is given by dividing each component by the length of the vector.

Calculates the length of a vector

If you want to draw a line from B to the left (when coming from A) you calculate the point P to draw the line to as

So you want to alternate that one time you draw to the left and one time to the right when iterating over the points.

If you have points lying outside your canvas, then you length is probably too large. You can of course calculate the point at which the vector to P would cross the boundary by calculating the intersection point of the vector BP and the border.

like image 172
Andreas Avatar answered Oct 05 '22 23:10

Andreas