Math Class
Objectives of this Objectives of this topic:topic:
Use the Math Class in Flash CS3
You can …
Use mathematical operators
Generate random numbers and round the numbers
OverviewOverviewIntroduction to Math ClassBasic Math OperatorsGenerating Random NumbersRounding Numbers
Introduction to Math ClassIntroduction to Math ClassMath Class is a built-in AS classIt simplifies a lot of task by
shortening and simplifying the codeIt contains:
◦methods representing common mathematical functions (log, max/min and round)
◦Properties representing mathematical constants (pi – 3.141…)
Example:var myInstance:MyClass = new myClass();◦This code creates a variable named
myInstance that is equal to a new instance of the class myClass
Math.random();◦This code creates a new instance of
a random number
Basic Math OperatorsBasic Math OperatorsBasic math operations simply can
be used in AS.Math operations are not
complicated to codeThe operations symbol include:
◦+ for addition◦- for subtraction◦* for multiplication◦/ for division
Flash follows the standard order of operations for arithmetic operation
There are four rules to the order of operations:◦ Solve the operations inside parentheses; ()◦ Solve the exponents; 22
◦ Perform the multiplication and division operations, working from the left to the right side of the equation
◦ Perform any addition and subtraction, also from left to right
Generating Random Generating Random NumbersNumbersUse a method of the Math class
to generate a random number; called random()
Example:trace(Math.random());◦run the Math class’s with randon()
function
Random number can contain, theoretically, an infinite number of decimal places, but they will never reach 1.0
Random numbers are great for generating random patterns or effect
Example:giving a direction and speed to individual snowflakes in a snowstorm.
To generate a whole random number, we can simply multiply the random method by 10
Exampletrace(Math.random() * 10);◦Generate a random numbers
between 0 and 10 (but not including 10)
Rounding NumbersRounding NumbersRounding technique uses to narrow
the result of number generated
Example:trace(Math.round(Math.random()*6));◦Math.round() uses the “nearest”
rounding technique for rounding numbers up and down (decimals from .0 to .4 are rounded down; decimals from .5 to .9 are rounded up)
Decimals are rounded to the nearest whole number, either:◦Round down – math.floor()
.0 to .9 are round down◦Round up – math.ceil()
.0 to .9 are round up
Flash: Math
Example of Math class implementation:
random_mc.addEventListener(MouseEvent.CLICK, onClick);
function onClick(event:MouseEvent):void{
dice1_mc.gotoAndStop(Math.ceil(Math.random()*6));}Rolling the dice (Rounding,
RoundingTwo)
Example of GamesExample of GamesMemoryGame
Source:◦MemoryGame◦Card◦Memory