Tutorials Books Videos Forums

Change the theme! Search!
Rambo ftw!

Customize Theme


Color

Background


Done
Look, an author!

Calculating the Distance between Objects

by trundrumbalind   | filed under Flash and ActionScript

Mathematical functions within Flash seems to be an area that most people like to stay well clear of. Of course, this area of Flash can be very daunting and difficult to get a hold of, so to ease you in, I thought I'd write a tutorial that takes a mathematical theory that we all know and mix it up with just enough Actionscript to help you into the thought-provoking world of maths in Flash without straying too far away from the graphical advantages it also offers.

Roll your mouse around the area below to see what I'm going to help you create:

[ an example of what you will create ]

Can you see what's happening? The transparency (alpha) of the different movieclips on the stage are changing depending on how close your mouse is to them! Pretty neat, eh?

Here is How

Ok, fire up Flash and let's get crackin:

  1. First off, open up your document properties by clicking on "Size" on the property manager when there's nothing selected. Change the dimensions to 325 x 240, change the framerate to 25 (just so our final movie is a little smoother) and click ok.
  2. Create a new movieclip by clicking on the "Insert" menu and selecting "New Symbol". Choose the "Movieclip" behaviour and enter a name of "circle".
  3. Using Flash's drawing tools, draw a borderless circle (it doesn't have to be red!) freehand on the stage. It doesn't matter if it's a perfect circle or even what size as you should now change it's width and height to 70x70 using the property inspector. To do so, just select your circle and type in these details like below:

    [ if you can't see the property inspector, hit Control+F3 ]

  4. Now center the circle on your stage by selecting it and then using the "Align Horizontal Center" and "Align Vertical Center" buttons on the "Align" panel shown below:

    [ bring up the align panel by hitting Control+K ]

  5. Create another movieclip. You can use the steps shown in step two but whilst you're messing around, why not learn a few shortcuts. This time, hit Control+F8 which will do the same thing. Give it a name of "distancing" and make it a movieclip. Hit OK.

Note

The movieclip you have just created isn't actually going to contain anything! Instead, we have created it so we can use a wicked piece of Actionscript called "onClipEvent (enterFrame)" (which is only available to movieclips). This allows us to have a set of commands executed over and over, each time the playhead of that movieclip is reached.

  1. Hopefully that note made sense to you, if it didn't come through too clear, don't worry! Things should become more evident soon. For now though, open up your library (Control+L) and change to your "circle" movieclip by double-clicking it.
  2. Now, whilst we're inside our "circle" movieclip, drag a copy (or "instance") of the "distancing" movieclip onto the stage. You now have a movieclip inside a movieclip!

So you made it this far then? Ok, let's get down to some coding. I promise to make it as easy as possible so don't sweat it.

At this point, you should have a movieclip called "circle" and inside it, you'll have a circle which is 70x70 and centered on the stage. You should also have an instance of the "distancing" movieclip inside here too. Here's what mine looks like:

[ the "circle" movieclip ]

Moving on:
  1. Ok, as I explained earlier, we're going to use the "distancing" movieclip to execute some code over and over again. This code, will be the code that calculates the distance between the mouse and this circle. The code will also then affect the circle's transparency (alpha) depending on this calculated distance so select the "distancing" clip by clicking on the white circle that represents it and open up the "Actions" panel by pressing F9 or open it from the "Window" menu.
  2. Insert the following code and why not have a quick glance at it yourself to see what you can pick up before I go over it in full?
    onClipEvent (enterFrame)
    		{
    
    
    			xdist =
    			Math.round(_root._xmouse
    			- _parent._x);
    
    
    			ydist =
    			Math.round(_root._ymouse
    			- _parent._y);
    
    
    			distancefromthis
    			= Math.round(Math.sqrt((xdist*xdist)
    			+ (ydist*ydist)));
    
    
    			_parent._alpha
    			= (100-distancefromthis)+20;
    }

    Do you recognize the formula used in fourth line? It's Pythagoras' theorem! What's that you say? Who's Pythagoras!? You should be ashamed! Never worry, here's what it is, how it works and how it applies here...

    Basically, Pythagoras' theory can be used to calculate the length of a side of a right-angled triangle given that we already know the two other sides. Here's a diagram:

    [ it has to be a right-angled triangle ]

    Pythagoras To The Rescue! OK, so we've got a right-angled triangle, two known sides (x and y) and an unknown hypotenuse (z). First of all, Pythagoras' theory is this:x² + y² = z²And here's our process of working out z: 130² + 180² = z² therefore... 16900 + 32400 = z² therefore... z = the squareroot of 49300 which equals 222

    Now let's imagine that our circle was at the top-left point of that triangle and the user's mouse was at the bottom-right point of the triangle, using that calculation and finding out "z" would give us the distance between the two! So let's figure out each of "x" and "y" individually then...

    First of all, "x" is the difference between the mouse's x value and the circle's x value. Therefore, we use the line:

    xdist =
    		Math.round(_root._xmouse
    		- _parent._x);

    Now for the "y" value. I think you can guess that it's the difference between the mouse's y value and the circle's y value. Therefore, we use the Actionscript:

    ydist =
    		Math.round(_root._ymouse
    		- _parent._y);
    Note You should note that I have used the _parent keyword in these lines. _parent basically makes your code refer to the current object's "parent" or whichever movieclip the current object is stored within.In this case, the code is on the "distancing" movieclip and this is placed inside the "circle" movieclip (it's parent). Therefore, _parent in this case refers to the "circle" movieclip.

    We now have the distance of the x co-ordinates in the "xdist" variable and the distance between the y co-ordinates in the "ydist" variable. Let's throw these details into Pythagoras' theory in the third line of our code. The distance between the mouse and the circle (or "z") will be stored in a variable called "distancefromthis". It will contain the square root of the "xdist" variable squared plus the "ydist" variable squared. In Actionscript, this looks like this:

    distancefromthis =
    		Math.round(Math.sqrt((xdist*xdist)
    		+ (ydist*ydist)));

    Notice that I have used the Math.round() function. This just rounds our result up or down to make everything a little tidier.

    Phew! I hope you're still with me--that was a lot to take in so pat yourself on the back. The final line of code which actually uses all our hard-earned data and affects the circle with it:

    _parent._alpha
    		= (100-distancefromthis)+20;

    Again, the use of the keyword _parent means that we're affecting the circle. Then, we point to the alpha property and set it to full (100) and then subtract the "distancefromthis" variable that we figured out and, as an option, I have added 20. This 20 number is something you should play about with to make things look how you want them. You can even try messing around with the entirety of this line!

  3. Now all that's left to do is to go back to your movie's root by clicking the "Scene 1" button at the top:

    [ clicking this from anywhere will bring you to the root ]

    And drag a bunch of the "circle" movieclips onto the stage. Test your movie and hey-presto! You should have the desired effect!

You're Done!

I hope this tutorial was of decent clarity to you as it is my first. Using this equation, you can really accomplish some great effects in Flash. How about having your script find out the distance between two characters in a platform game and have them react differently to each other depending on their proximity? As always with Flash, your imagination is the only limit.Below you can download the source code for this project. As an added bonus, my Flash file contains a little extra code on the first frame of the root timeline which actually places all your circles on the stage dynamically using the attachMovie() function.

Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence, ads, and algorithm-driven doodads. A huge thank you to all of you who buy kirupa's books, became a paid subscriber, watch the videos, and/or interact on the forums.

Your support keeps this site going! 😇

-trundrumbalind

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright KIRUPA 2026 //--