E: me@sabisin.com | T: +4915168651209

Actionscript 3 : Toggling a Boolean

No need of conditional statement to figure out which direction to toggle a Boolean value.

var iStRue:Boolean;
iStRue = !iStRue;
trace(iStRue);      //true
iStRue = !iStRue;
trace(iStRue);      //false

Device Shake – Accelerometer

Heres a small snippet to detect shakes on mobile devices with accelerometer:

var lastShake:Number = 0;
var shakeWait:Number = 600;
 
var acc:Accelerometer = new Accelerometer();
acc.addEventListener(AccelerometerEvent.UPDATE, onAccUpdate);
 
function onAccUpdate(evt:AccelerometerEvent):void
{
	if(getTimer() - lastShake > shakeWait && (evt.accelerationX >= 1.5 || evt.accelerationY >= 1.5 || evt.accelerationZ >= 1.5))
	{
		sHakeiT();
		lastShake = getTimer();
	}
}
 
function shakeIt()
{
	trace("shakeIt();");
}

as3: removing duplicates from an array

Removing duplicate items from an array in one line of ActionScript 3

var tMpaRr:Array = ["a","b","b","c","b","d","c"];

var aRr:Array = tMpaRr.filter(function (a:*,b:int,c:Array):Boolean { return ((aRr ? aRr : aRr = new Array()).indexOf(a) >= 0 ? false : (aRr.push(a) >= 0)); }, this);

trace(aRr); //a,b,c,d

Minimum or Maximum value from an array of numbers

First, note that Math.min() and Math.max() can take any number of arguments. Also, it’s important to understand the apply() method available to Function objects. It allows you to pass arguments to the function using an Array. Let’s take advantage of both:

var aRr:Array = [2,3,3,4,2,2,5,6,7,2];
var mAxvAlue:Number = Math.max.apply(null, aRr);
var mInvAlue:Number = Math.min.apply(null, aRr);

Here’s the best part: the “loop” is actually run using native code (inside Flash Player), so it’s faster than searching for the minimum or maximum value using a pure ActionScript loop.

ActionScript 3 : Get a Class Reference by Class Name

If you need to get a reference to a class in ActionScript 3, but only know the class name, then you can use the flash.utils.getDefinitionByName to create an instance of the class. For example:

package {
	import flash.display.Sprite;
	import flash.utils.getDefinitionByName;

	public class DynamicCall extends Sprite
	{
		public function DynamicCall()
		{
                    var ClassReference:Class = getDefinitionByName("ClassName") as Class;
		}
	}
}

Example :

var ClassReference:Class = getDefinitionByName("String") as Class;
var str:String = (new ClassReference("SAbi Sin") as String);
trace(str);

This basically creates an instance of the String class, from the class name “String”. getDefinitionByName takes the entire class path, so if you wanted to create an instance of MovieClip, you would provide the entire path:

var ClassReference:Class = getDefinitionByName("flash.display.MovieClip") as Class;

Simple useful Snippet.