Suppose we have an object with hitbox having an arbitrary complex shape and an object with circle/polygon as a hitbox. How to detect the collisions of these two objects (not the boundary rectangles, but the actual pixels)? Both objects are opaque Sprites.
Here is a snippet of code I found in ActionScript 3 (https://snipplr.com/view/90435/pixel-perfect-collision-detection-as3/) that looks like it should work in OpenFL.
A Haxe version of the code might look like this:
public function objectsHit (mc1:DisplayObject, mc2:DisplayObject):Bool {
var mc1bounds = mc1.getBounds (this);
var mc2bounds = mc2.getBounds (this);
var allintersections = (mc2bounds.intersection(mc1bounds));
for (xval in allintersections.x...(allintersections.x + allintersections.width)) {
for (yval in allintersections.y...(allintersections.y + allintersections.height)) {
if (mc2.hitTestPoint (xval, yval, true) && mc1.hitTestPoint (xval, yval, true)) {
return true;
}
}
}
return false;
}
It might also be possible to use the hitTestObject
method first, then to use the hitTestPoint
method second. The general idea is to perform bounding box hit detection first, then to perform point-based collision (which is more expensive) if you need something more exact.