简体   繁体   中英

AS3: Getting a color value from a bitmap

I'm attempting to retrieve a color value when I click an image on the stage. I'm planning to use this to create a height map for a game I'm working on, making the character move slower over rough terrain (portions of the height map with a specific color value), but I keep getting the following error:

TypeError: Error #1034: Type Coercion failed: cannot convert flash.display::MovieClip@2fc84f99 to flash.display.Bitmap.
at testGetColor2_fla::MainTimeline/frame1()

Here's my code so far:

import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.events.MouseEvent;
import flash.display.Sprite;

var container:Sprite = new Sprite();

var myHeightMap:Bitmap = Bitmap(heightMap);

this.addChild(container);
container.addChild(myHeightMap);

container.addEventListener(MouseEvent.CLICK, onClick);

function onClick(e:MouseEvent):void
{
    var obj:Sprite = e.currentTarget as Sprite;

    var myHeightMap:Bitmap = Bitmap(obj.getChildAt(0));

    var pixelValue:uint = myHeightMap.bitmapData.getPixel(mouseX,mouseY);

    trace(pixelValue.toString(16));
}

What am I doing wrong?

The way how you doing it is not quite right :)

This is how you convert the the MovieClip to Bitmap:

function toBitmap(value:DisplayObject):Bitmap
{
    var bmpData:BitmapData = new BitmapData(value.width, value.height, true, undefined);
    bmpData.draw(value, null, null, null, null, true);

    return new Bitmap(bmpData, "auto", true);
}

And then you can get the pixel.

Remember that RegistrationPoint must be TOP_LEFT.

The problem is that you can't just convert a MovieClip to a Bitmap by casting it like you're trying to do when creating myHeightMap . To do that conversion, use the following:

var bitmapData:BitmapData = new BitmapData(heightMap.width, heightMap.height);
bitmapData.draw(heightMap);
var myHeightMap:Bitmap = new Bitmap(bitmapData);

Of course, there might be other ways to do this. If you could find a way to have heightMap as a Bitmap before this code is called, that would be more efficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM