Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 861
TechBee Avatar asked Nov 04 '22 18:11

TechBee


1 Answers

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.

like image 142
Rob Napier Avatar answered Nov 13 '22 05:11

Rob Napier