Craig
Craig

Reputation: 51

Only detecting collision with the visible part of a transparent image (AS3)

I have a transparent image and a square. I'm wanting to detect when the square collides with the image. However, because the image is transparent it would still detect it colliding with the transparent pixels. So, after some reading I've attempted using BitmapData, which I haven't used before. And so, it isn't working. To be honest I didn't expect the bellow code to work. I just wrote to give you an idea of what I wanted to do and how I wanted to it.

Here's my code:

package 
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.events.Event;

/**
 * Testing Transparency
 * @author Craig Jackson
 */

public class Main extends Sprite 
{
    public var square:Sprite;

    [Embed(source="../lib/TestTransparency.png")]
    public var TestTrans:Class;

    public var testTransBitmapData:BitmapData = new BitmapData(300, 30, true, 0);

    public var testTransBitmap:Bitmap = new TestTrans();

    public function Main():void 
    {
        if (stage) init();
        else addEventListener(Event.ADDED_TO_STAGE, init);
    }

    private function init(e:Event = null):void 
    {
        removeEventListener(Event.ADDED_TO_STAGE, init);
        startUp();
    }

    public function  startUp():void 
    {
        square = new Sprite();
        square.graphics.beginFill(0x666666);
        square.graphics.drawRect(0, 0, 50, 50);
        square.graphics.endFill();
        addChild(square);

        testTransBitmapData.draw(testTransBitmap);
        addChild(testTransBitmap);

        addEventListener(Event.ENTER_FRAME, enterFrame);
    }

    public function enterFrame(e:Event):void
    {
        square.x = mouseX;
        square.y = mouseY;

        if (square.hitTestObject(testTransBitmap))
        {
            trace("Touching");
        }
    }
}

Anyone know how I can make the it detect only when the square collides with visible part of the image? Massive thanks in advance.

Upvotes: 1

Views: 693

Answers (1)

Rahul Banerjee
Rahul Banerjee

Reputation: 2363

Unless you have a personal reason for wanting to implement this yourself, I'd recommend using Corey O'Neil's collision detection kit:

https://code.google.com/p/collisiondetectionkit/

Upvotes: 1

Related Questions