[AS3] Find distance between two points
Some time ago I have needed to find the distance between two points. I found two ways to do this:
With the AS3, the Point class was implemented to make more ease the coordenates manipulation. Inside this class has one method called distance that can be used to find the desired distance.
var point1:Point = new Point(0, 0); var point2:Point = new Point(10, 10); var distance:Number = Point.distance(point1, point2);
2. The optimized way (5x faster):
Surfing on the web I found another method that use the Pythagorean Theorem making execution code speediest. We too can use this method when we dont have a Point instanciated you can use x and y properties of any display object.
var point1:Point = new Point(0, 0); var point2:Point = new Point(10, 10); var distance:Number = distance(point1.x, point1.y, point2.x, point2.y);
This is the magic function:
function distance (x1:int, y1:int, x2:int, y2:int):Number { var dx:int = x2 - x1; var dy:int = y2 - y1; return Math.sqrt(dx*dx + dy*dy) }
You must be wondering why the easiest and speediest execution methods are listed here. Ok, I done one simple test to prove the difference of time execution between the two ways where you can see:
Lopping 10000000 times in each method this results are printed:
Finding distance using Point.distance:
[distance=14.142135623730951, execution time: 5673ms]
Finding distance using Pythagorean Theorem:
[distance=14.142135623730951, execution time: 1623ms]