AS3 BitmapData碰撞

时间:2014-02-15 10:53:57

标签: actionscript-3 bitmap collision-detection bitmapdata

我遇到了BitmapData碰撞检测问题,我的班级根本没有发现任何碰撞

BitmapCollision.as

package com.ipromoweb.demoapp 
{
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.Rectangle;
/**
 * ...
 * @author Me
 */
public class BitmapCollision {

    private var collides:Boolean = false;

    public function check(obj1:DisplayObjectContainer, obj2:DisplayObjectContainer):Boolean {
        // obj1
        var obj1Rect:Rectangle = obj1.getBounds(obj1);
        var obj1Offset:Matrix = obj1.transform.matrix;
        obj1Offset.tx = obj1.x - obj1Rect.x;
        obj1Offset.ty = obj1.y - obj1Rect.y;

        var obj1ClipBmpData:BitmapData = new BitmapData(obj1Rect.width, obj1Rect.height, true, 0);
        obj1ClipBmpData.draw(obj1, obj1Offset);

        // obj2
        var obj2Rect:Rectangle = obj2.getBounds(obj2);
        var obj2Offset:Matrix = obj2.transform.matrix;
        obj2Offset.tx = obj2.x - obj2Rect.x;
        obj2Offset.ty = obj2.y - obj2Rect.y;

        var obj2ClipBmpData:BitmapData = new BitmapData(obj2Rect.width, obj2Rect.height, true, 0);
        obj2ClipBmpData.draw(obj2, obj2Offset);

        var rLoc:Point = new Point(obj2Rect.x, obj2Rect.y);
        var bLoc:Point = new Point(obj1Rect.x, obj1Rect.y);

        if (obj1ClipBmpData.hitTest(bLoc, 255, obj2ClipBmpData, rLoc, 255)) {
            trace("hit");
            collides = true;
        }else {
            collides = false;
        }

        obj1ClipBmpData.dispose();
        obj2ClipBmpData.dispose();

        return collides;
    }

}

}

我在ENTER_FRAME事件上调用checkCollision函数,hitTestObject触发得很好,但bitmapData Collision根本没有触发。

    private function checkCollision():void {
        for (var i:int = 0; i < parent.numChildren; i++) {
            if (Object(parent.getChildAt(i)).constructor == '[class CollisionTest]') {
                if (this.hitTestObject(parent.getChildAt(i))) {
                    trace('colliding');
                    if ( _collision.check(Sprite(this),Sprite(parent.getChildAt(i))) ) {
                        trace('>>>>>>>>>>> perfect hit');
                    }
                }

            }
        }
    }

对此的任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我放弃了之前尝试实现的BitmapData Collision方法并下载了一个名为CDK的免费库:

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

它解决了我所有的问题。