Basic random functions

Here are some really basic (but useful) functions that returns random stuff…

The really basic one, is built in the Flash api and it returns a Number between 0 and 1:

var n:Number = Math.random();

A number in  a range

Sometime is more useful to have a random number in a different range, let’s say between 15 and 45, instead of 0 and 1.

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

Random int

and what if we don’t need decimals? Round’em!

public static function randInt(max:Number = 1, min:Number = 0):int {
    return Math.round(Math.random() * (max - min) + min);
}

Random boolean

True or false? Flip a coin.

public static function bool():Boolean {
    return (Math.round(Math.random()) == 0);
}

Random sign

-1 or 1; Useful when you have to random select random rotation verse, for example, -1*45 or 1*45, rotates counterclockwise or clockwise.

public static function sign():Number {
    return (Math.round(Math.random()) == 0):-1:1;
}

Random color

Really useful when drawing debug shapes on screen..

public static function color():uint {
    return Math.random() * 0xFFFFFF;
}

Random point

Inside an area. I like to use the flash.geom.Rectangle struct to describe an area, more than using 4 parameters (Flash api are quite inconsistent about this choice)

public static function point(area:Rectangle):Point {
    return new Point(randInt(area.x, area.x + area.width), randInt(area.y, area.y + area.height));
}

Quickreference: display elements in a circle

How to display elements in a circle? A small function to do that is:

public static function circle(items:Array, center:Point, distance:Number = -1, initialAngle:Number = 0):void {
var step:Number = (2* Math.PI) / items.length;
var angle:Number = initialAngle;
for each (var d:DisplayObject in items) {
if (distance < 0) distance = d.height+10 / Math.sin(step);
d.x = center.x + distance * Math.cos(angle);
d.y = center.y + distance * Math.sin(angle);
angle += step;
}
}

Parameters are:

  • items: the items to be displayed a a circle
  • center: the center of the circle
  • distance: the distance from the center
  • initialAngle: the angle of the first item. Zero means that the item wil be aligned orizontally with the center, on his right.

Here’s an example:

Tweening global volume in flash

Just a quick reminder on how to shut up the master volume on a flash project. I like a smooth tween to the silence, so I’m using the TweenLite libraries.

private function volumeOff():void {
    var sf:SoundTransform = new SoundTransform();
    TweenLite.to(sf, 1, {volume:0, onUpdate:applySoundTransform, onUpdateParams:[sf]});
}

private function applySoundTransform(s:SoundTransform):void {
    SoundMixer.soundTransform = s;
}

The trick here is to tween the volume property of a throw-away SoundTransform object, and on each step of the Tween apply that object as the SoundMixer.soundTransform Object, with an helper function. Note that I’m not going to write the function inside the TweenLite’s partameter list, as it is gross and dirty.

Tweening the volume back to 1 is so easy that I’m not writing it, to not offend anyone.

Quick reference: Drawing a scaled object in Actionscript

Just as a quick reference, since I usually forgot each time how to do it.

Assume to have a DisplayObject obj, you want to draw in a Bitmap a scaled snapshot of that object.

Just like when you are drawing thumbs.

public function drawScaled(obj:DisplayObject, thumbWidth:Number, thumbHeight:Number):Bitmap {
var m:Matrix = new Matrix();
m.scale(thumbWidth / obj.width, thumbHeight / obj.height);
var bmp:BitmapData = new BitmapData(thumbWidth, thumbHeight, false);
bmp.draw(obj, m);
return new Bitmap(bmp);
}

Fading out and detaching

One class i really do like is TweenLite. I don’t really like the default tweening engine for a couple of reasons, but mainly because i have to save the tween object in a reference in my class, or the garbage collector could eat it (stopping the tweens in a unpredictable status).
TweenLite don’t require this (it exposes static functions, and keep internal references to the tweens) and permits me to specify functions to be called, not only handlers (which i know, may sound a little ActionScript 2.0, but in fact permits to call any funcion, and so avoiding one-line handlers).

One small example, (to be used inside a DisplayObjectContainer) is fading out a child, and detaching after. In one clear line:

TweenLite.to(mySprite, 1, {alpha:0, onComplete:removeChild, onCompleteParams:[mySprite], delay:0.5});

Let’s bring this a step further: we can easily apply this technique to all child of a given container:

package
{
    import flash.display.DisplayObject;
    import flash.display.Sprite;
    import gs.TweenLite;

    public class mySprite extends Sprite
    {
        public function mySprite()
        {
            super();
        }

        public override function removeChild(child:DisplayObject):DisplayObject {
            TweenLite.to(mySprite, 1, {alpha:0, onComplete:super.removeChild, onCompleteParams:[child], delay:0.5});
            return child;
        }

    }
}

So now all the time removeChild is called from outside, the child gently fade away, and then quietly removes himself.