Search code examples
objective-ciosipad

Collision detection of uneven shapes in iOS


enter image description here

I am working on drag and drop activity for iPad. I have a rectangle PNG image (see the image named as obj2). When I drag obj1 only on the black portion of the rectangle then it should react.

if (CGRectIntersectsRect(obj1.frame, obj2.frame))
{
    NSLog(@" hit test done!! ");
}

Right now, this piece of code takes hit test even on the transparent area. How to prevent that to happen?


Solution

  • For something as simple as your specific example (triangle and circle), the link that David Rönnqvist gives is very useful. You should definitely look at it to see some available tools. But for the general case, the best bet is clipping, drawing, and searching.

    For some background, see Clipping a CGRRect to a CGPath.

    First, create an alpha-only bitmap image. This is explained in the above link.

    Next, clip your context to one of your images using CGContextClipToMask().

    Now, draw your other image onto the context.

    Finally, search the bitmap data for any colored pixels (see the above link for example code).

    If any of the pixels colored, then there is some overlap.


    Another, similar approach (which might actually be faster), is to draw each image into its own alpha-only CGBitmapContext. Then walk the pixels in each context and see if they ever are both >128 at the same time.