00:00
00:00
Newgrounds Background Image Theme

Marco07red just joined the crew!

We need you on the team, too.

Support Newgrounds and get tons of perks for just $2.99!

Create a Free Account and then..

Become a Supporter!

AS3: Math Functions

19,916 Views | 2 Replies
New Topic Respond to this Topic

AS3: Math Functions 2012-03-30 14:06:52


AS3: Math Functions
-----------------------------
AS3: Main
-----------------------------

AS3 have lots of classes, a very useful one is called the Math class. It contains mathematical functions and values. Also every Math method is static and must be called with Math.method(parameter) if it is a function and Math.constant if it is a constant value.

The class contains a bunch of functions and constants. I'm not going to show them in alphabetical order, but separated by relation.

I think that the most used are floor(), round() and ceil().

Floor, Round and Ceil
All of the them return the value specificied in the parameter, the only thing which will change is how they were.

Floor: the floor is the closest integer that is less than or equal to the specified number or expression.

Round: rounds the value of the parameter up or down to the nearest integer and returns the value. If the value is equidistant from its two nearest integers (that is, if the number ends in .5), the value is rounded up to the next higher integer.

Ceil: returns the ceiling of the specified number or expression. The ceiling of a number is the closest integer that is greater than or equal to the number.

If they're explanations sound confusing here it is a great example of how do they work:

var floor:Number = Math.floor(0.00087);
var round:Number = Math.round(1.00087);
var ceil:Number = Math.ceil(1.00087);

// floor of 0.00087,
// round and ceil of 1.00087

trace('floor: '+floor);
trace('round: '+round);
trace('ceil: '+ceil);

/* 
floor only returns the integer, 0
round rounds the value to 1
ceil rounds the value to 2
*/

You use them when you have, for example, a decimal number but you want to display only an integer. Let's say you are tracing a movie clip's coordinates with:

trace(new Point(mc.x,mc.y));

It might display you an enormous decimal number but you do:

trace(new Point(Math.floor(mc.x),Math.floor(mc.y));

Then you only will get the integer of the coordinates. Or you can use the Number(expression).toPrecision(precision) method.

Have you ever wanted to display numbers in a specific length? Like 57.23423423 to 57.23? So:

var n:Number = 57.23423423;
trace(n.toPrecision(4)); // outputs 57.23

===//===//===//===

Pi
One of the greatest numbers of all, lol. Comes as one of the constant values from the class.

Math.PI; // returns 3.141592653589793

Extremely useful. You can use that as the constant for helping to draw a circunference, to measure the area of a circle (A = pi * r ^ 2), etc...

You can also use it to convert radians to degrees or degrees to radians.

toDegrees = radians * 180 / Math.PI
toRadians = degrees * Math.PI / 180

I'll cover with more focus this convertion part in another tutorial about Trigonometry.

===//===//===//===

Trigonometric functions
Trigonometric functions are Math's class functions used to return values like cosine, sine and tangent of an angle in radians.

The functions are:
* acos --> arc cosine
* asin --> arc sine
* atan --> arc tangent
* atan2 --> arc tangent 2
* cos --> cosine
* sin --> sine
* tan --> tangent

===//===//===//===

Pow and SQRT
The Math.pow(base, expoent) function returns the base powered to the exponent. This means that if you do for example pow(2,3) it will return 8 from 2 * 2 * 2. Although it is much faster type something like: a = 4 * 2, then doing Math.pow(2,3). This function is slower than just typing the values. It is very recommended to use it when you have unknown values or variables. You can also use it for scientific notation.

var pow1:Number = Math.pow(2,3);
trace(pow1); // returns 8

// -------------

var n:Number = 1;

// updating each frame: (...)
n++;

trace(Math.pow(.915, n)); 

// -------------

var pow3:Number = Math.pow(.001,-2);
trace(pow3); // returns 1000000

===//===//===//===

SQRT, the Square Root
Math.sqrt() computes and returns the square root of the specified number.

Examples:

var sqrt1:Number = Math.sqrt(4); 
trace(sqrt1); // returns 2

var sqrt2:Number = Math.sqrt(Math.PI * 235.67 + 1);
trace(sqrt2); // returns 27.228278327347592

var sqrt3:Number = Math.sqrt(-3);
trace(sqrt3); // returns NaN

var sqrt4:Number = -Math.sqrt(3);
trace(sqrt4); // returns -1.7320508075688772

A really useful thing for using the square root function is for getting resultant vectors (like distance separated by x and y coordinates, a graphic resultant vector, etc...) through the pytaghorean theorem:

hyphotenuse ^ 2 = side A ^ 2 + side B ^ 2

var y1:Number = 50;
var y2:Number = 125;

var x1:Number = 100;
var x2:Number = 412;

// distance squared, distance non-squared
var d:Number = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
var d2:Number = Math.sqrt(d);

You can also use the pow function above:

var d:Number = Math.pow(x2-x1,2) + Math.pow(y2-y1,2);
var d2:Number = Math.sqrt(d2);

===//===//===//===

Absolute value
Let's say you want to get the difference between a point coordinates according to the mouse, you would do for example:

var deltaX:Number = mouseX - point.x

But if you trace deltaX, you will get negative values while the mouse is in its left and positive if mouse is in its right.

So if you only want to get positive values, you use Math.abs:

var deltaX:Number = Math.abs(mouseX - point.x);
trace(deltaX); // will only return you positive values

Also if you know that some value may get negative values but you don't want to, is just apply the Math.abs function.

===//===//===//===

Random value
You can get a random value using Math.random().

Example:

var randomNumber:Number = Math.floor(Math.random() * 5);
trace(randomNumber); // any value between 0 and 5

If you want to get a random value in a specific range, which is VERY useful for, for example, spawning movie clips only inside the screen canvas, you can write a function like this:

static public function getRandomNum(min:Number, max:Number):Number
{
         return Math.floor(Math.random() * (1 + (max - min))) + min;
}

Let's say you want to spawn movie clips from coordinates 5 to the maximum possible inside the stage width:

getRandomNum(0, stage.stageWidth);

===//===//===//===

Minimum and Maximum
Let's say you want to get the minimum or maximum value from something, like an array, you can do something like this:

// array with random numbers where min = -3 and max = 15
var array:Array = [-1, -3, 2, 3, 4, 5, 6, 7, 8, 15, 10];

// init two variables for min and max
var min:int = int.MAX_VALUE; 
var max:int = int.MIN_VALUE;

for(var i:int = 0; i < array.length ; i++)
{
        // min and max can be any value from the array but just picking up their respective integers
	min = Math.min(array[i], min); 
	max = Math.max(array[i], max);
	
        // if loop is complete, output min and max
	if(i == array.length - 1)
	{
		trace('min: '+min); // returns -3
		trace('max: '+max); // returns 10
	}
}

===//===//===//===

Additional functions
There are some less used functions from the Math.class but which are useful for some things. Like log and exp (logarithm and exponentials respectively).

var log2:Number = Math.log(2);
var log3:Number = Math.log(3);
var log10:Number = Math.log(10);

var exp:Number = Math.exp(log2);

trace('log2: '+log2);
trace('log3: '+log3);
trace('log10: '+log10);
trace('exp log2: '+exp);

And there are some very unknown and forgotten functions like SQRT1_2 lol.

In the Math class, Euler's angle constant can also be found:

var E:Number = Math.E;
trace(E); // returns 2.718281828459045

Response to AS3: Math Functions 2012-03-30 14:09:30


If you are going to work with big mathematical expressions you can also set the class variables as function variables, like this:

var cos:Function = Math.cos;
var sin:Function = Math.sin;
var sqrt:Function = Math.sqrt;

var sqrt25:Number = sqrt(25); 
trace(sqrt25); // returns 5

===//===//===//===

Well that is it. I hope it was useful and that you learned something from it. There might be some grammar typos, if you don't know what I said, I can try explaining again.

I tried covering all the essential functions. Thanks for reading.

Response to AS3: Math Functions 2012-03-30 14:18:31


lol just fixing a math typo in minimum and maximum, it is not outputs 10, it is 15. :P