< Introduction to ActionScript 2.0
Key concepts:
Maths are very important in Flash applications. Let's learn how to use mathematical functions in ActionScript!
Handling numbers
There are several functions of the Math class that can manipulate numbers for us:
- Math.abs(Number): Finds the absolute value of a number
- Math.ceil(Number): Rounds a number up to the nearest integer
- Math.floor(Number): Rounds a number down to the nearest integer
- Math.round(Number): Rounds a number off to the nearest integer
- Math.max(Number 1, Number 2): Returns the larger of two numbers
- Math.min(Number 1, Number 2): Returns the smaller of two numbers
- Math.random(): Returns a random number smaller than 1 and larger than or equal to 0
Let's look at a quick example:
Code | Result |
---|---|
var myNumber:Number = -12.3;
trace(Math.abs(myNumber));
trace(Math.ceil(myNumber));
trace(Math.floor(myNumber));
trace(Math.round(myNumber));
trace(Math.max(Math.ceil(myNumber), Math.floor(myNumber)));
trace(Math.min(Math.ceil(myNumber), Math.floor(myNumber)));
trace(Math.floor(Math.random() * 12)+1);
|
|
Note the technique used in the last line to produce random numbers. Math.random() is multiplied by 12, rounded down (giving a random integer from 0 to 11) and then one is added (giving a random integer from 1 to 12).
Exponents, roots and logarithms
Trigonometry and pi
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.