Here's a quick-n-simple piece of AS3 (or javascript) 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>
Previous Entry
Flash mobile tip number 1
Next Entry
How to make a game design document
Advertisement
Latest Entries
Neato transition effect
3475 views
New Unity3D UI and just general musing.
4380 views
So Dwarf Planet Pirates has grown in scope.
3805 views
Seems to still be working.
2664 views
Advertisement