Home > OS >  Detect Colour Using Action Script 3
Detect Colour Using Action Script 3

Time:09-17

So I have made a game in scratch which uses the following code block:

Scratch Code Exmaple

I am trying to remake this game in Adobe Animate using Action Script 3 (for a class project), is there a similar way to do this in animate?

CodePudding user response:

It is possible. The trick to do it is to create a tiny-teeny BitmapData object and to draw a small portion of stage under the mouse pointer into that object so that you can obtain the pixel color value.

// BitmapData object and some service objects.
var BD:BitmapData = new BitmapData(3, 3, true);
var R:Rectangle = new Rectangle(0, 0, 3, 3);
var M:Matrix = new Matrix;

// Let's create a TextField so we can output the pixel color value.
var T:TextField = new TextField;
var TF:TextFormat = new TextFormat("_typewriter", 12, 0x000000, true, false, false, null, null, TextFormatAlign.CENTER);

T.x = 10;
T.y = 10;
T.width = 100;
T.height = 18;
T.border = true;
T.background = true;
T.selectable = false;
T.mouseEnabled = false;
T.defaultTextFormat = TF;

addChild(T);

// Lets add some semi-transparent color circles
// so we have colored things to point the mouse at.
for (var i:int = 0; i < 10; i  )
{
    var aColor:uint = 0;
    
    aColor |= int(128   128 * Math.random()) << 16; // RED
    aColor |= int(128   128 * Math.random()) << 8;  // GREEN
    aColor |= int(128   128 * Math.random());       // BLUE
    
    var anX:int = stage.stageWidth  / 8   Math.random() * stage.stageWidth  * 3 / 4;
    var anY:int = stage.stageHeight / 8   Math.random() * stage.stageHeight * 3 / 4;
    var aRadius:int = 50   100 * Math.random();
    var anAlpha:Number = 0.5   0.5 * Math.random();
    
    graphics.beginFill(aColor, anAlpha);
    graphics.drawCircle(anX, anY, aRadius);
    graphics.endFill();
}

// Now let's watch the mouse every frame.
addEventListener(Event.ENTER_FRAME, onFrame);

function onFrame(e:Event):void
{
    // Get pixel color as an RRGGBB String and print it.
    T.text = "#"   addZeroes(getColorUnderMouse());
}

function getColorUnderMouse():uint
{
    // Adjust Matrix so that we draw the correct piece of screen.
    M.tx = -root.mouseX   1;
    M.ty = -root.mouseY   1;
    
    // Clear the BitmapData and capture the 3x3 piece under the mouse pointer.
    BD.fillRect(R, 0xFFFFFFFF);
    BD.draw(root, M, null, null, R);
    
    // Read the pixel color value at the center of 3x3 and return it.
    return BD.getPixel(1, 1);
}

// This function fixes the hexabinary value with leading
// zeroes if the color value is too small (like 0 = black).
function addZeroes(value:uint, count:uint = 6):String
{
    var result:String = value.toString(16).toUpperCase();
    
    while (result.length < count)
    {
        result = "0"   result;
    }
    
    return result;
}
  • Related