Amar
Amar

Reputation: 11

ActionScript 3.0/Flash Builder give an object a random color

How could randomly change the color of object in as3.

Upvotes: 1

Views: 2500

Answers (2)

ToddBFisher
ToddBFisher

Reputation: 11590

I agree with Shane. I would also add my prefered method of changing colors dynamically using flash.geom.colorTransform.

This allows you to change colors for any shape, including irregular ones without having to know exact dimensions. You can use the following method, combined with Shane's random number generator code, to pwn this task.

import flash.geom.ColorTransform;   
const INVALID_HEX_COLOR_VALUE:uint = 16777216;  //Value that exceeds color range (over #FFFFFF)

function applyColorSchemeTo(obj:DisplayObject, otherColor:uint = INVALID_HEX_COLOR_VALUE):void {
    if(obj != null){
        var colorTransform:ColorTransform = obj.transform.colorTransform;
        if(otherColor < INVALID_HEX_COLOR_VALUE)
        {
            colorTransform.color = otherColor;
            obj.transform.colorTransform = colorTransform;
        }           
    }
}

Upvotes: 1

shanethehat
shanethehat

Reputation: 15570

You can generate a random valid color like this: Math.round(Math.random()*0xFFFFFF).

For example, this draws 5 randomly colored squares:

for(var i:int = 0; i < 5; i++) {
    var num:uint = Math.round(Math.random()*0xFFFFFF);
    trace(num.toString(16));
    var mc:Shape = addChild(new Shape()) as Shape;
    mc.graphics.beginFill(num);
    mc.graphics.drawRect(100*i,0,80,80);
}

Alternatively, if you need more control of the color ranges there is an working class here: QuasiUseful : AS3 Random Color Generator

Upvotes: 3

Related Questions