Determine When one DisplayObject Totally Overlaps Another

I had a recent issue where I needed to know when one DisplayObject was totally over another, and more importantly prevent the object being transformed from uncovering the other DisplayObject. I like simple, so let’s get to the pictures. The box below is being transformed:

image

The problem is initially that the fixed DisplayObject not being moved is irregular in shape. This becomes apparent when trying to drag, scale, or rotate the square. If my drag restricts the drag area to the bounds of the fixed DisplayObject, this is great until I rotate the other DisplayObject which then invalidates the drag bounds and you can see below that a corner is uncovered.

image

What I need to do is detect if the transform move would result in uncovering the fixed DisplayObject and thus not allow it. If both items where rectangles and not being rotated we could use something like the following to detect the total overlap:

  1. boxA.transform.pixelBounds.containsRect(boxB.transform.pixelBounds);

This provides a very nice boolean result, and in my test kinda worked. It just wasn’t 100%.

However, between considering that solution and considering hitTest, and then being reminded of Grant Skinner’s AS2 pixel perfect collision detection, I realized how I could do this.

The collision detection code, upgraded and improved by Troy Gilbert (code and article here) to AS3 provided the key. First, it provides great detection. Then I realized that the method returns a rectangle that represents the overlap of my two DisplayObjects.

If I compare the overlap rectangle to the fixed position DisplayObject rectangle, and make sure it’s not smaller, then I know the object being transformed is fully covering it. Rotate, scale, drag, scale some more, drag, rotate a little, drag, and it locks in step never uncovering the fixed position DisplayObject (which btw is a mask).

Once I get a little breathing room I’ll put up a Flash demo and my code for how I’m using it. Hopefully my hurried explanation here makes some sense. I’m just jazzed I got it working, and all the help I received via Twitter contributed to the final solution.

» continue reading
Categories: FlashPermalink