electronslibres.ca ça mute avec l'AS3

6Mar/102

Tips’n'Tricks

Here some actionscript code snippets and/or tricks I stumbled upon, or found by myself. I may use it as a reminder ;)

// (via @zeh)
//count only "drawn" frames
NetStream.decodedFrames  
 
//complete frame count
NetStream.info.droppedFrames

Here is a snippet to force the browser's focus when leaving fullscreen mode :

stage.addEventListener(MouseEvent.CLICK,toggleFullScreen);
 
function toggleFullScreen(event:MouseEvent):void
{ 
	switch (stage.displayState) 
	{ 
		case "normal" : 
			stage.displayState = fullScreen"; 
			break; 
 
		case "fullScreen" : 
 
		default : 
			stage.displayState = "normal"; 
			ExternalInterface.call("focus");
			break; 
	} 
}

Remove all childs from a DisplayObject:

while( myDisplayObject.numChildren ) myDisplayObject.removeChildAt(0);

Self Removal:

this.parent.removeChild( this );

Retreive self index

this.parent.getChildIndex( this );

String Trick:
appendText() is always faster than text+= ;

A must Read : Thibault Imbert's white paper on Optimizing Mobile Content for the Adobe Flash Platform which contains usefull information on optimization for mobile phones, and desktop apps as well!

MATHS FUNCTION INLINED VERSIONS

// almost 8 times faster than the Math.version
// benchmark can be found here : http://www.calypso88.com/?p=539 
Math.pow(i, 2);
i * i; 
 
Math.min(i, 50000);
(i > 50000) ? 50000 : i;
 
Math.max(i, 50000);
(i < 50000) ? 50000 : i;
 
Math.abs(i);
(i < 0) ? -i : i ;
 
Math.floor(i);
int( i );
 
Math.ceil(i);
(i % i) ? int(i) + 1 : i;
 
Math.round(i);
int(i + .5);

OTHER BITWISE OPERATIONS

//Fast modulo operation using bitwise AND
 
//If the divisor is a power of 2, the modulo (%) operation can be done with:
//modulus = numerator & (divisor - 1);
 
x = 131 % 4;
x = 131 & (4 - 1);
 
 
//Check if an integer is even/uneven using bitwise AND
isEven = (i % 2) == 0;
isEven = (i & 1) == 0;
 
 
//Right bit shifting to divide by any power of two:
x = x / 2;
x = x >> 1;
 
x = x / 64;
x = x >> 6;
 
 
//Left bit shifting to multiply by any power of two
 
x = x * 2;
x = x << 1;

Using MODULO GRIDS is faster than multidimensional array

const ROWS:int = 30;
const COLUMNS:int = 88;
const ITEMS:int = ROWS * COLUMNS;
 
var s:Shape ;
var i:int = 0;
 
for(i; i < ITEMS; i++)
{
   s = new Shape();
   s.x = int(i / ROWS) * 5;
   s.y = (i % ROWS) * 5;
   s.graphics.beginFill(0x666666);
   s.graphics.drawRect(0, 0, 4, 4);
 
    addChild(s);
}