Creating a Pesky Ad Part 2

OK, this is part 2 of the tutorial.

First off, we're going to find out how to calculate the distance that is between the mouse and the cancel-button.

Calculating the distance

onClipEvent (enterFrame) {
 

We use onClipEvent handlers, like the one above, when placing some code on Movieclips. In the parenthesis we sort of specify the type of the handler. Because in this tutorial we want the code to be executed every frame, we write enterFrame in the parenthesis.

distance = Math.sqrt(Math.pow(_root.advert.button._y-_root.advert._ymouse), 2)+Math.pow(_root.advert.button._x-_root.advert._xmouse, 2));
 

Although it might look a bit complicated, I assure you it's not!

First of all, let's get down to all of these "math things". After that I'm going to explain why this code is such and not otherwise.


Math.sqrt(x) - this method computes and returns the square root of the specified number. So, if I were to type:

trace(Math.sqrt(2))

Flash would return approx. 1.42.



Math.pow(x, y)- this method computes and returns x to the power of y. As you might predict, the following code:

trace(Math.pow(2, 3))

... returns 2*2*2=8.



Now, let's see why the variable distance is equivalent to all the stuff on the right side of the equation.


As you might probably have noticed by now, distance is in fact calculated by Pythagoras Theorem. Briefly, the theory says that:

 

 

If we change this equation a little bit, we will receive:

c = square root(a2 + b2)

Now, you might be able to see some resemblence to the Actionscript code we are discussing. In fact, it is the same - expect for different variables.


The picture below illustrates how the code works.

 

 

Do you know what the variable distance is equal to in the above image?

Let's think...

x coordinate difference is 200-120 = 80

y coordinate difference is 300-230 = 70

So, from Pythagoras Theorem, the variable distance is equal to:

distance = square root(80*80 + 70*70), which gives us approx. 106.


So, this is basically how the distance is calculated. What we now need to do is use this variable. How to do that? Read on to find out!

Average: 4 (1 vote)