Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Find the slope a1 of AB by dividing the y-difference with the x-difference; then draw a perpendicular line (with slope a2 = -1/a1, you need to solve for the offset (b2) by putting P's coordinates into y = a2*x + b2); then you have two lines (i.e. two linear equations), and you need to solve the intersection. That will be your closest point.</p> <p>Do the math right, and the function will be pretty trivial to write.</p> <p>To elaborate a bit:</p> <pre><code>Original line: y = a1 * x + b1 a1 = (By - Ay) / (Bx - Ax) &lt;-- b1 = Ay - a1 * Ax &lt;-- Perpendicular line: y = a2 * x + b2 a2 = -1/a1 &lt;-- b2 = Py - a2 * Px &lt;-- Now you have P which lies on both lines: y = a1 * x + b1 y = a2 * x + b2 --------------- subtract: 0 = (a1 - a2) * Px + (b1 - b2) x = - (b1 - b2) / (a1 - a2) &lt;-- y = a1 * x + b1 &lt;-- </code></pre> <p>Hope I didn't mess up somewhere :) <strong>UPDATE</strong> Of course I did. Serve me right for not working things out on paper first. I deserved every downvote, but I'd've expected someone to correct me. Fixed (I hope).</p> <p>Arrows point the way.</p> <p><strong>UPDATE</strong> Ah, the corner cases. Yeah, some languages don't handle infinities well. I did say the solution was language-free...</p> <p>You can check the special cases, they're quite easy. The first one is when the x difference is 0. That means the line is vertical, and the closest point is on a horizontal perpendicular. Thus, <code>x = Ax, y = Px</code>.</p> <p>The second one is when y difference is 0, and the opposite is true. Thus, <code>x = Px, y = Ay</code></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload