Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's Ruby disguised as Pseudo-Code, assuming <code>Point</code> objects each have a <code>x</code> and <code>y</code> field.</p> <pre><code>def GetClosestPoint(A, B, P) a_to_p = [P.x - A.x, P.y - A.y] # Storing vector A-&gt;P a_to_b = [B.x - A.x, B.y - A.y] # Storing vector A-&gt;B atb2 = a_to_b[0]**2 + a_to_b[1]**2 # **2 means "squared" # Basically finding the squared magnitude # of a_to_b atp_dot_atb = a_to_p[0]*a_to_b[0] + a_to_p[1]*a_to_b[1] # The dot product of a_to_p and a_to_b t = atp_dot_atb / atb2 # The normalized "distance" from a to # your closest point return Point.new( :x =&gt; A.x + a_to_b[0]*t, :y =&gt; A.y + a_to_b[1]*t ) # Add the distance to A, moving # towards B end </code></pre> <hr> <p>Alternatively:</p> <p>From <a href="http://en.wikipedia.org/wiki/Line-line_intersection" rel="noreferrer"><strong>Line-Line Intersection</strong></a>, at Wikipedia. First, find Q, which is a second point that is to be had from taking a step from P in the "right direction". This gives us four points.</p> <pre><code>def getClosestPointFromLine(A, B, P) a_to_b = [B.x - A.x, B.y - A.y] # Finding the vector from A to B This step can be combined with the next perpendicular = [ -a_to_b[1], a_to_b[0] ] # The vector perpendicular to a_to_b; This step can also be combined with the next Q = Point.new(:x =&gt; P.x + perpendicular[0], :y =&gt; P.y + perpendicular[1]) # Finding Q, the point "in the right direction" # If you want a mess, you can also combine this # with the next step. return Point.new (:x =&gt; ((A.x*B.y - A.y*B.x)*(P.x - Q.x) - (A.x-B.x)*(P.x*Q.y - P.y*Q.x)) / ((A.x - B.x)*(P.y-Q.y) - (A.y - B.y)*(P.y-Q.y)), :y =&gt; ((A.x*B.y - A.y*B.x)*(P.y - Q.y) - (A.y-B.y)*(P.x*Q.y - P.y*Q.x)) / ((A.x - B.x)*(P.y-Q.y) - (A.y - B.y)*(P.y-Q.y)) ) end </code></pre> <p>Caching, Skipping steps, etc. is possible, for performance reasons.</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