Handy piece of code

Published August 04, 2010
Advertisement
Here's a quick-n-simple piece of AS3 (or &#106avascript) that calculates the point on a line closest to a given point. It took me a couple of tries to get it right, so I figured I would share it.<br><br><!--STARTSCRIPT--><!--source lang="javascript"--><div class="source"><pre><span class="cpp-keyword">var</span> nearestPtToLine = <span class="cpp-keyword">function</span>(segA:Point, segB:Point, p:Point, infinite:<span class="cpp-keyword">Boolean</span> = <span class="cpp-keyword">true</span>):Point<br>{<br> <span class="cpp-keyword">var</span> dx:Number = segB.x - segA.x<br> <span class="cpp-keyword">var</span> dy:Number = segB.y - segA.y<br> <span class="cpp-keyword">var</span> u:Number = ((p.x - segA.x) * dx + (p.y - segA.y) * dy) / (dx * dx + dy * dy)<br><br> <span class="cpp-keyword">if</span> (!infinite)<br> {<br> <span class="cpp-keyword">if</span> (u > [[<span class="cpp-number">1</span>]])<br> u = [[<span class="cpp-number">1</span>]]<br> <span class="cpp-keyword">else</span> <span class="cpp-keyword">if</span> (u < [[<span class="cpp-number">0</span>]])<br> u = [[<span class="cpp-number">0</span>]]<br> }<br> <span class="cpp-keyword">return</span> <span class="cpp-keyword">new</span> Point(segA.x + u * dx , segA.y + u * dy)<br>}<br><br><br></pre></div><!--ENDSCRIPT--><br><br>seg1 and seg2 define a line segment. p is the point to test. infinite assumes that the line extends beyond seg1 and seg2. If you need the distance from a point to a line, just use the distance function in the flash.geom.Point object.<br><br><br>EDIT: I don't know why gamedev's source formatter is putting brackets around the 1's and 0's in the if (!infinite) block. Don't do that. Just regular ones and zeros.<div> </div>
0 likes 0 comments

Comments

Nobody has left a comment. You can be the first!
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!
Advertisement