devxlogo

Master Simple Math Concepts to Electrify Your ActionScript

Master Simple Math Concepts to Electrify Your ActionScript

any Flash creators?even experienced ActionScript coders?are unnecessarily frightened by math. Some find the subject so intimidating they will avoid even simple scripting projects if there is any “serious” math involved. However, I think those same Flashers would be surprised by how much they could accomplish, and how easily, by understanding just a small handful of math and (dare I say it?) physics principles.

Understanding a few basic formulas can really bring your ActionScript to a higher level. For example, you can easily add an approximation of gravity, acceleration or friction to games for a much greater level of realism and polish. You can calculate the distance between two points to improve collision detection, and path finding making more complex interactions within reach. Best of all, you can replace the restrictive nature of timeline animations with highly dynamic ActionScript that let you change any parameter you desire at runtime?and let you reuse and adapt the code for many other projects.

Thus begins an occasional look at math made easy within these pages. From time to time, I will show how seemingly confusing science can be much easier to comprehend than you thought. How often I visit these topics depends on your feedback to these articles, so let me know what you think.

Sine and Cosine

Figure 1. Sine and Cosine Illustrated: What could be easier? Potentially complicated graphics like this one are the reason many programmers stay away from mathematic concepts in their designs.

I’ll start by explaining some very simple trigonometry that is enormously useful in animation, game programming, and even interface design. Don’t panic thinking about the word trigonometry. I’ll only be using two functions in this article: sine and cosine. Figure 1 should make these principles easy to understand. (Or not.)

Trying to digest a comprehensive illustration or description of a concept, such as that in Figure 1, is one of the biggest barriers to embracing math in every day scripting. Ultimately, it would be great to have a full understanding of each topic, how each applies to our environment, etc. But it often helps to start with only the information that relates to what you’re trying to accomplish and then move on from there if a need presents itself.

For example, in the case of sine and cosine, it’s better to begin by understanding the roles of sine and cosine in the composition of a triangle. If you can think of a simple triangle and start working with x and y coordinates, for example, suddenly you’re getting somewhere!

Triangles
A lot of discussion about triangles in trigonometry is about the relationship between the sides of the triangle, the angles of the triangle, or some combination of both. If you have any experience in these topics, you may remember the three sides being described as a, b, and c, with c being the longest side. In the context of this article, it will be easier to think about this if you imagine the triangle on the Flash stage. Hereafter, I’ll show the x and y axis, and label the triangle sides x, y, and c, with c still being the longest side.

Figure 2. Single Point: The screen shot shows a point on the Flash stage, described by position x, y.

Look at Figure 2. If you wanted to position a MovieClip at a point on the stage, you need to know its x and y coordinates.

See also  Custom Java Web Development - The Heartbeat of Modern Web Development

One way of determining those values is by using an angle described by the triangle formed with x and y as two of it sides, as shown in Figure 3. If you know the angle indicated in green and marked with a (40-degrees, for example, but I’ll talk about that later), you can use the sine and cosine functions to determine x and y.

Figure 3. X and Y: Using angle a, you can determine x and y with the cosine and sine functions..

This is because the cosine of the angle is defined as x over c, and the sine of the angle is defined as y over c. For simplicity, c is defined as having a length of 1, making the cosine of the angle x, and the sine of the angle y.

Fortunately, you don’t have to worry about the formulas for sine or cosine because these functions are built into Flash, in the Math object. So, all you have to do is use the provided methods on your angle:

MovieClip._x = Math.cos(angle)MovieClip._y = Math.sin(angle)

Now that you know how simple it is to get x and y coordinates from an angle, think of how easy it would be to animate a MovieClip on a circle. All you have to do is keep calculating the sine and cosine of a series of angles, and this will describe a circle as depicted in Figure 4.

Figure 4. Circular Path: A circular animation path is easy to create with sine and cosine.

Since c is 1 in the definition of sine and cosine, and c is the radius of the circle, you can create a circle of any size simply by multiplying the resulting sine and cosine values by the radius you want. For example, if you simply multiply your sine and cosine values by 100, you will describe a circle with a radius of 100.

Now you can animate MovieClips around any point on the stage, another MovieClip, or your mouse. You can even turn boring old left-aligned navigation systems into a dynamic arc of moving buttons. All of these examples will be included in source code that you can download from this article.

The Flash Coordinate System and Angle Measurements
Before I go any further, it’s important to describe two things about how Flash (and most other computer environments) deal with coordinates and angles. First, you must remember that, unlike the graphs you used in math, in Flash, positive y values are down, not up. The origin point (0,0) of the Flash stage is the upper left corner, so positive angles begin in the lower right quadrant of the stage and increase as you rotate clockwise around the stage (see Figure 5). Negative angles can be specified, but they don’t really exist. That is, it’s not possible to have a negative angle in the real world, but if you specified -45°, Flash would understand you to mean 315°.

Second, while you can use degrees as an angle unit of measure for the MovieClip._rotation property, all of the trig functions require a unit of measure called radians. There are 2 ? radians in 360 degrees, and therefore ? radians in 180 degrees.

Author’s Note: You may remember that ? (pi, approximately 3.14) is a unique mathematical constant that expresses the ratio of the circumference of a circle to its diameter. It is helpful to understand it when calculating the circumference (2 ?r) and area (?r2), but all you need to remember now is that there are 2 ? radians in 360 degrees. In ActionScript, the ? constant can be retrieved from the Math object by referencing Math.PI (case-sensitive).
See also  Custom Java Web Development - The Heartbeat of Modern Web Development
Figure 5. Going Up: In the Flash coordinate system, positive angles start in the lower right quadrant of the screen and the angle values increase with a clockwise rotation.

To pass an angle to the aforementioned Math.sin() and Math.cos() methods, you must use radians. However, since most of us are used to thinking in terms of degrees, it can be more convenient to convert degrees to radians. To do so, multiply the angle in degrees by (?/180).

Circular Animation with ActionScript
Now that you know how to convert degrees to radians, I can show you the small script that will animate a MovieClip in a circle. If you don’t want to start from scratch, you can download the source code and follow along. Otherwise, start a new Flash file and call it “circle1.fla.” Add a MovieClip to the stage (my file uses a 40-pixel circle), and give it an instance name of “mc1.” Next, add the following script to frame one of your movie. I’ll explain as I go.

To start, I’ll store a few simple variables in the MovieClip.

mc1.angle = 0;mc1.angleChange = 20;mc1.radius = 100;mc1.centerX = Stage.width / 2;mc1.centerY = Stage.height / 2;

The first line establishes an arbitrary angle at which you will begin the animation. Remember that positive angles start at positive x, zero y and rotate clockwise (covered in the last section).

The second and third lines define a degree of change in the angle from one iteration of the script to the next, and the size (radius) of the circular animation path.

The third and fourth lines define the point around which the “mc1” MovieClip will animate?in this case, the center of the stage.

Next, I’ll define a simple function to convert degrees to radians and return the radian value. Remember that Math.PI is a constant that is already part of the built-in Math class.

function deg2rad(degree) {     return degree * (Math.PI / 180);}

Next I’ll define the function that will actually animate the MovieClip.

function animateCircle() {     var radian = deg2rad(this.angle);     this._x = this.centerX + this.radius * Math.cos(radian);     this._y = this.centerY + this.radius * Math.sin(radian);     this.angle += this.angleChange;     this.angle %= 360;}

After the function definition (which I’ll omit from these line counts) the first line stores the degree to radian conversion in the local variable, radian. It passes the current value of the angle variable stored in the MovieClip to the conversion function. This variable starts as 0, but will be incremented with each iteration of the animation.

The second and third lines update the x- and y-coordinates of the MovieClip, starting with the center of the orbit, adding the radius offset, and then the x and y location, respectively, determined by taking the cosine and sine, respectively, of the current angle (in radians, of course).

The fourth line uses the += assignment operator to add the MovieClip angleChange value to the MovieClip angle variable.

The last line of the function is another great example of how not being afraid of math can improve your code. All this line does is make sure the angle value stays within the range of 0-360. It might otherwise have been written:

if (this.angle >= 360) {     this.angle = 360 - this.angle     this.angle = this.angle - 360}

Instead, it uses the modulus assignment (%=) to say, in one simple line, ‘reassign the variable to the amount left over (the remainder) when dividing the value of the variable by 360.’ For example, if, after adding 20, the angle value is 380, you may want to adjust that so the final value is within the accepted range of 0-360 (380 divided by 360 equals 1 with a remainder of 20). Therefore, using modulus, the new value of this.angle can be set to 20. This can be very handy. Using modulus can reduce the amount of code you have to write (and, therefore, maintain) and it’s really useful for common every day tasks. For example, you can quickly determine if any number is even or odd. Any even number when divided by 2 will leave a remainder of 0, while any odd number divided by 2 will leave a remainder of 1.

See also  Custom Java Web Development - The Heartbeat of Modern Web Development

Back to our script, the last line of the script assigns the aforementioned function to the EnterFrame event of the MovieClip so it is called every time the playback head enters a frame in the MovieClip?thereby causing a frame loop.

mc1.onEnterFrame = animateCircle;

That’s it! Test your movie, and you should see the MovieClip animating in a circle around the center of the stage.

More Examples
I’ve also included two more examples in the downloadable source code, but they use almost exactly the same code. This shows how versatile the code can be and how easy the math is to use.

The second example does nothing more than add another MovieClip that uses the same code, but continuously centers the second MovieClip around the first. This results in a satellite around the satellite, much like the Moon revolving around the Earth while the Earth revolves around the Sun (albeit with perfectly circular orbits). The effect can be interesting. Try varying the values of angleChange and radius for the second MovieClip and see how that changes the animation.

The third example goes back to one MovieClip but adds a subtle wrinkle by varying the value of radius during the animation. The effect is a spiral animation path–first in and then back out.

When you’re comfortable with the changes that make these animations unique, you can download two additional samples from my Web site (http://www.fmaonline.com/devx/) to move on to something slightly more complicated. One will orbit the MovieClip around the mouse, instead of the center of the stage, and the other will use the same circle math to create an interesting dynamic interface. It will take a random number of buttons and place them, equidistantly, around the circular path you’ve created. Trust me, it’s easy!

Was I Right?
I hope you agree that, if you learn the small bits and pieces of math that are most relevant to your needs, you can gain great benefits with relatively small amounts of pain. If you liked this article, let me know. If there is enough interest, I can move on to things like gravity, springs, friction, collisions and more?all of which will be much easier than you think and will add tons of creative options to your Flash animations!

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist