Quick tip: Find the distance between two points in Flash
Published on Fri 08 Oct 2010 by Will
When programming in Actionscript 3.0 you will at some point need to find the distance between two arbitrary points on the stage. This is most true when developing applications with dynamic graphics such as Flash games. Here are two methods of finding the distance between two points on the stage.
Method 1: The easy way
Flash comes with a native Point class which, as the name suggests, represents a point in two dimensional space. A Point takes two parameters in it’s constructor, one for the x value of the point the other for the y value.
To find the distance between two Point instance we call the static distance method of the Point class like so:
var point1:Point = new Point(50, 150); var point2:Point = new Point(300, 400); var distance:Number = Point.distance(point1, point2);
Method 2: The slightly less easy way
There will often be occasions where you don’t already have existing Point instances to work with. Take any DisplayObject for example. DisplayObjects, by their nature, already contain x and y values representing their registration point in 2D space. Now we could go ahead and create a Point instance based on these values such as:
var point1:Point = new Point( mc1.x, mc1.y); var point2:Point = new Point( mc2.x, mc2.y); var distance:Number = Point.distance(point1, point2);
But doing this is inefficient as we are creating two Point instance just to satisfy the required parameters of the distance method of the Point class. An alternate way to calculate the distance is by using the following formula:
var dx:int = x2 - x1; var dy:int = y2 - y1; var distance:Number = Math.sqrt(dx*dx + dy*dy);
To better promote code reuse we can convert the above into an easily reusable function like so:
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)
}
We can then simply call our distance method, passing in two sets of x and y values to find the distance between them.
var distance:Number = distance( mc1.x, mc1.y, mc2.x, mc2.y );
There you have it, two methods for finding the distance between two points in Flash using Actionscript 3.0.
Did you enjoy this post?
Why not subscribe via RSS or follow Ahrooga on Twitter for alerts on new posts :)







Comments
My co-worker and I were trying to figure this out the other day. Thanks!