I have a line that I draw in a window and I let the user drag it around. So, my line is defined by two points: (x1,y1) and (x2,y2). But now I would like to draw "caps" at the end of my line, that is, short perpendicular lines at each of my end points. The caps should be N pixels in length.
Thus, to draw my "cap" line at end point (x1,y1), I need to find two points that form a perpendicular line and where each of its points are N/2 pixels away from the point (x1,y1).
So how do you calculate a point (x3,y3) given it needs to be at a perpendicular distance N/2 away from the end point (x1,y1) of a known line, i.e. the line defined by (x1,y1) and (x2,y2)?
If you want to avoid a sqrt, do the following:
Since the vectors from 2 to 1 and 1 to 3 are perpendicular, their dot product is 0.
This leaves you with two unknowns: x from 1 to 3 (x13), and y from 1 to 3 (y13)
Use the Pythagorean theorem to get another equation for those unknowns.
Solve for each unknown by substitution...
This requires squaring and unsquaring, so you lose the sign associated with your equations.
To determine the sign, consider:
Known: point 1 : x1 , y1
Known: point 2 : x2 , y2
Known: distance |1->3| : N/2
equation a: Pythagorean theorem
Known: angle 2-1-3 : right angle
vectors 2->1 and 1->3 are perpendicular
2->1 dot 1->3 is 0
equation b: dot product = 0
ratio b/w x13 and y13:
equation a: solved for y13 with ratio
equation a: solved for x13 with ratio
to condense
I normally wouldn't do this, but I solved it at work and thought that explaining it thoroughly would help me solidify my knowledge.
You need to compute a unit vector that's perpendicular to the line segment. Avoid computing the slope because that can lead to divide by zero errors.
You just evaluate the orthogonal versor and multiply by N/2