There will be times when you need to know how far apart two items are. While it is common in games or situations involving collision detection, you will run into needing to know the distance more often than you think. For example, the Random Movement animation is a case where the distance between two points is used to gauge when to change direction:

In this short tutorial, you will learn how to use the Pythagorean Theorem to calculate the distance when you know the x and y coordinates of two points.
A full explanation and more about the Pythagorean Theorem can be found on Wikipedia, but in a nutshell, the equation looks as follows:

Your distance is the square root of the net horizontal distance squared and your net vertical distance squared. Continuing the example we started off with, the xa, xb, ya, and yb values can be visualized as follows:

The code for converting our equation into the ActionScript that Flash understands is as follows:
Two simplify our expression, I create two variables called xDiff and yDiff that store the difference in the x and y positions between the two points:
Once I have the difference, the rest of the math is very straightforward:
Below, you will find a larger example that demonstrates finding the distance between two points at (0, 100) and (0, 100):
That's all there is to finding the distance between two points. If there is anything you take away from this tutorial, just ask yourself, wasn't Pythagoras one smart dude?
Note
For calculating squares, there is the Math.pow function that
could be used instead of multiplying the same values twice.
The original version of this tutorial used that approach
actually:
The reason this approach was not the one presented above is due to performance. Using the simpler multiplying approach, my informal tests showed a gain of around 30 - 40%. While it may not be accurate using the approach I used to measure this, at least it gives you a ballpark. Thanks to @_robfox who pointed this out to me via Twitter.
Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence slop, ads, and algorithm-driven doodads. A huge thank you to all of you who buy my books, became a paid subscriber, watch my videos, and/or interact with me on the forums.
Your support keeps this site going! 😇

:: Copyright KIRUPA 2026 //--