Article

Perform Math Calculations in Flash

Page: 1 2 3

The Code

  1. Name the current layer in the movie “content”. Add a new layer to the movie, and call it “actions”.

    1124_image11

  2. Select the first frame of the “actions” layer. In the Actions panel, add the following code:

    function onCalculate() {  
     one = Number(number_one);  
     two = Number(number_two);  
     result_sum = one + two;  
     result_product = one * two;  
    }

    This is the code that will make this movie do its magic! Let’s look at what this code does and why.

    function onCalculate() {

    This first line starts a new function in the movie. Remember that we gave our PushButton component a Click Handler of “onCalculate”. When this button is clicked, it will execute the code within this function.

    one = Number(number_one);  
    two = Number(number_two);

    This code has two purposes. The first is to give shorter variable names to the data that’s being calculated. Instead of spelling out “number_one” throughout our code, we can now just use “one”.

    This makes more sense when taken in conjunction with the second purpose: to treat these variables as numbers. This is done with Number(), which tells Flash that we to treat values in parentheses as numbers. If we don’t, when we calculate 1 plus 1, we’ll get 11. Or, if we calculate 1 plus 2, we’ll get 12. Instead, with the Number(), when we calculate 1 plus 1, we’ll get 2.

    result_sum = one + two;  
    result_product = one * two;  
    }

    Remember the variable names we gave the two textboxes at the bottom? This code puts our calculation results within those textboxes. When this code is executed, the “result_sum” textbox will display the result of adding Number 1 and Number 2. The “result_product” textbox will display the result of multiplying them.

That’s it! Publish your movie, type in some numbers in first two textboxes, and hit Calculate.

1124_image12

Again, if you get lost, download the sample FLA.

Final Thoughts

There is your quick and dirty run down of basic math in Flash. There is not a single calculation that Flash cannot handle. This tutorial only scratches the surface, but I hope it’s got you thinking about Flash math. For more information, try:

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Rate This Article

  • 1
    Poor
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
    Great

Comment on This Article

Have something to say?

Post A Comment

You need to be a member of the SitePoint Forums to comment on this post. Sign Up

Already a member? Post using your SitePoint Forums account: