title: Point on a line closest to x,y
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/910882/how-can-i-tell-if-a-point-is-nearby-a-certain-line">How can I tell if a point is nearby a certain line?</a>  </p>
  </blockquote>
  
  
  
  <pre><code>//Returns the point on the line traced from start to end which
  //comes nearest to 500,000, 500,000. The points are scaled between
  //1,000,000 and 0 from their original fp types.
  Point closestToCentre(Point start, Point end);
  </code></pre>
  
  <p>Anyone know of quicker way than single stepping through the pixels?</p>
  
  <p>Could some one more alert than me demonstrate their maths &amp; geometry prowess please?</p>
  
  <p>_______EDIT___________</p>
  
  <p>Thanks Kris, this was confusing me : </p>
  
  <p>[x; -a/bx-c/b]=[0; -c/b]-1/b[-b; a]x. </p>
  
  <p>Now I see it is just splitting (mainly the y component) the vector into two which combine to yield the same result. Got the old partial fractions brain cell excited for a minute then :)</p>
  
  <p>_______EDIT_________</p>
  
  <p>Jason Moore, thanks for the inspiration, here is what I am doing, graphically,</p>
  
  <p><img src="https://i.stack.imgur.com/5HaoK.png" alt="64x64 square with 2 sample lines each passing edge to edge and missing the centre by some distance"></p>
  
  <p>I hope that is clearer.</p>
  
  <p>____EDIT________</p>
  
  <p>So I could reasonably expect to take a line at right angles to my sampled line and run it from the centre but how to tell when they touch?</p>
  
  <p><img src="https://i.stack.imgur.com/2RfKI.png" alt="enter image description here"></p>
  
  <p>I think Kris's page of equations is the way to go. If you're all telling me it is a two step process. It is just two simultaneous equations now, so I may not need Kris's derivations.</p>
  
  <p>____EDIT_________</p>
  
  <p>Whether good or bad thing, I don't know, but the beauty of stackoverflow as a search engine has revealed to me several routes of investigation. Chiefly I like the first solution here:
  <a href="https://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment">Shortest distance between a point and a line segment</a>.</p>
  
  <p>But to prove this to my self I needed the link from matti's solution at the bottom (but one):</p>
  
  <p><a href="http://www.topcoder.com/tc?d1=tutorials&amp;d2=geometry1&amp;module=Static" rel="nofollow noreferrer">http://www.topcoder.com/tc?d1=tutorials&amp;d2=geometry1&amp;module=Static</a></p>
  
  <p>The derivation is so simple and elegant even I could follow it!</p>
  
  <p>Given <a href="http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html" rel="nofollow noreferrer">http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html</a></p>