Nodebay
Nodebay

Reputation: 554

Sprite movement on mask

I have an Avatar class that extends the Sprite class. I also have a Room class that contains a Bitmap of "walkable" areas and non-walkable areas, as well as the room's artwork itself.

I need to make sure that the user can only walk on the white/transparent parts of the room "mask," without actually showing the black and white mask. What functions can I use to ensure that the user doesn't go into the black parts of the mask, quickly?

Upvotes: 0

Views: 71

Answers (2)

Organis
Organis

Reputation: 7316

Lets say your Avatar:Sprite is properly aligned around its own (0,0) point. Then you create a Walkable:Sprite with a shape of walkable areas. It must be attached to the display list, but not necessarily visible, you can set Walkable.visible = false.

function moveBy(dx:Number, dy:Number):void
{
    var aPoint:Point = new Point();
    aPoint.x = Avatar.x + dx;
    aPoint.y = Avatar.y + dy;

    // hitTestPoint works with Stage coordinates.
    aPoint = Avatar.parent.localToGlobal(aPoint);

    if (Walkable.hitTestPoint(aPoint.x, aPoint.y, true))
    {
        Avatar.x += dx;
        Avatar.y += dy;
    }
}

This code is very simple, it just disallows to move your Avatar out of Walkable map.

Upvotes: 1

Alexandr Mostovoy
Alexandr Mostovoy

Reputation: 11

You just need to have this 'walkable' bitmap in memory

private const ALLOWANCE:Number = .1;
private function isTurnAllowed(maskBMD:BitmapData, position:Point):Boolean
{
    //0xAARRGGBB
    var color32:uint = maskBMD.getPixel32(int(position.x), int(position.y));
    var alpha:uint = color32  >> 24 & 0xff;
    var red:uint = color32 >> 16 & 0xff;
    var green:uint = color32 >> 8 & 0xff;
    var blue:uint = color32 & 0xff;

    var color24:uint =color32 >> 8 & 0xffffff;

    /*
    if (alpha == 0 || color24 == 0xffffff) return true

     strictly speaking this string is enough but in real your bitmap mask after resampling can have some interpolation artifacts so you need some  allowance to pass not strictly white.
     */
    var absoluteLightness:Number = red +  green + blue + (0xff - alpha);//transparent is 0x00
    var maximalLight:Number = 0xff * 4;
    var lightness:Number = absoluteLightness / maximalLight;
    if (lightness > 1 - ALLOWANCE)
        return true
    else
        return false

}

Upvotes: 1

Related Questions