Length of a Diagonal Line in Flash

Posted in Tutorial.

I’m working on a project in Flash right now where I have an object that needs to follow a motion path of a diagonal line. It’s sounds really easy, but the object is only suppose to move in increments, controlled by user-supplied data, which requires some ActionScripting. This also means that we need to dynamically get the length of the diagonal line because it’s length may vary. If you think that simply using the _width property works, you’re wrong! The _width property only looks at the x-axis of an object, obviously not taking the y-axis of the diagonal line into account.

Remember The Pythagorean Theorem?

Does this ring any bells? Yeah, I haven’t used it since I graduated from college either. In fact, I specifically went into graphic and web design so I wouldn’t have to remember it. Wikipedia does a much better job explaining it than I ever could:

The sum of the areas of the two squares on the legs (a and b) equals the area of the square on the hypotenuse (c).

Here’s a horrible diagram that I did up quickly that might make it easier to understand what we’re talking about.

Pythagorean Theorem

Now What?

In Flash, start by drawing the right triangle with the desired length of the hypotenuse. It makes it a lot easier if you do this with no fill. Next, select each side of the triangle and convert them into separate movie clips and give each one an instance name. I named mine: Triangle_x (corresponding with the line on the x-axis), Triangle_y (corresponding with the line on the y-axis) and hypotenuse (the diagonal line), respectively. Then we take the formula of the Pathagorean Theorem and apply it to our ActionScript:

var xaxis = Math.ceil(Triangle_x._width * Triangle_x._width);
var yaxis = Math.ceil(Triangle_y._height * Triangle_y._height);
var hypotenuse = Math.ceil(Math.sqrt(xaxis + yaxis));

For the variable xaxis we want to get the width of the horizontal line and multiply it by itself, which is the same thing as squaring it. For the variable yaxis we do the same that we did for xaxis, except that we want the height since it is a vertical line. For the variable hypotenuse we want the square root of xaxis and yaxis added together. It’s also important to note that we’re using the Math.ceil function to round all of our numbers up — this will make life a lot easier not having to deal with repeating decimal numbers.

We could just use the hypotenuse as our motion guide, but for whatever reason, it appears that flash can not retrieve properties of a motion guide. The easy solution is to just copy the hypotenuse and paste it into a new layer to use it as your motion guide. Finally, set the alpha level for the three movie clips (that make up the triangle) to zero so that they won’t be visible. Anytime you wish to access the length of the diagonal line (hypotenuse), it can be referenced by the variable hypotenuse. Simple, right?