Given 2 points how do I draw a line at a right ang

2019-01-17 12:19发布

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

标签: geometry
1条回答
疯言疯语
2楼-- · 2019-01-17 13:02

It's a question of vector mathematics. You can calculate the directing vector between two points A and B by subtracting B from A. 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.

查看更多
登录 后发表回答