Flash CS4 ActionScript 3.0 Tutorial
How to Add, Subtract, Multiply, and Divide Numbers with ActionScript in Flash
Often times you need to perform simple math operations in ActionScript. The symbols for common operations are as follows:
In math class, you may have been asked to create two variables and assign a value for each. Then run them through and equation and calculate a solution. It might look like this.
a = 5
b = 6
a + b = 11
To accomplish the same thing in ActionScript, the code would look a little different.
It is helpful to see the equals sign as the statement "is replaced by" when evaluating an equation. The following example uses parentheses to determine the order that the equation is solved.
Name the default layer, Actions.
Option double-click (PC - Alt double click) the first keyframe of the Actions layer to open the ActionScript panel.
Copy/Paste the following code in the ActionScript Panel:
totalValue=(a * b)/(c + d);
Test your movie by pressing Cmd/Return (PC - Ctrl/Enter). The value of totalValue appears in the Output panel.
Dissecting the Code
The first five lines at Step Three establish five new variables and set a value for each.
To solve for totalValue, 40 is multiplied by 5 (200), then 14 is added to 6 (20). Finally, 200 is divided by 20, giving us a total of 10. The last line displays the value of totalValue in the Output window.
There are multiple ways to add a value to a number variable. For instance, you may want to add two to a number variable each time a function is run. You could write the code using Method One or Method Two.
Method One (10 + 2 = 12)
Method Two (10 + 2 = 12)
The second method is easier than the first. The same is true for subtraction, multiplication and division.
Subtraction (10 - 2 = 8)
Multiplication (10 * 2 = 20)
Division (10 / 2 = 5)