试试这个。纹理精灵来自Flambe引擎。本质上是碰撞的边界框,然后遍历碰撞框,检查每个像素。
static public function pixelPerfect(sprite1:SpriteContainer, sprite2:SpriteContainer):Bool
{
var collisionRect:Rectangle;
for (texture1 in sprite1.textures)
{
for (texture2 in sprite2.textures)
{
collisionRect = CollisionUtil.collisionRect(texture1, texture2);
if (collisionRect == null) continue;
if (pixelCollision(texture1, collisionRect) && pixelCollision(texture2, collisionRect))
{
return true;
}
}
}
return false;
}
static public function pixelCollision(sprite:TextureSprite, collisionRect:Rectangle)
{
var localRectPt:Point = sprite.globalToLocal(collisionRect.x, collisionRect.y);
localRectPt.x /= Main.GLOBAL_SCALE;
localRectPt.y /= Main.GLOBAL_SCALE;
var scaledRect:Rectangle = collisionRect.clone();
scaledRect.width /= Main.GLOBAL_SCALE;
scaledRect.height /= Main.GLOBAL_SCALE;
var PIXEL_DATA_LENGTH:Int = 4;
var PIXELS_TO_SKIP:Int = 5;
var resolution:Int = PIXEL_DATA_LENGTH * PIXELS_TO_SKIP;
var alphaOffset:Int = 3;
var bytes:Bytes;
try{
bytes = sprite.symbol.atlas.readPixels(Math.round(localRectPt.x), Math.round(localRectPt.y), Math.round(scaledRect.width), Math.round(scaledRect.height));
var n:Int = bytes.length;
var i:Int = 0;
while(i+3<n)
{
if (bytes.get(i + alphaOffset) > 0)
{
return true;
}
i += resolution;
}
}
catch (e:Dynamic)
{
Log.trace(e);
}
bytes = null;
return false;
}
}