user3259290
user3259290

Reputation: 11

How to check intersection of two images that aren't rectangular?

New user to the site, but I have used it in the past so I felt it best to ask my question here, for the best chance of getting a response.

What I'm dealing with is one object, this being the sprite for my latest app, which I need to check for when it comes in to contact with another object, in this case, a tunnel which will curve.

Now, I'm aware of CGRectIntersectsRect, however I can't see that being helpful, as if I've got 2 UIImages, that being the top and bottom of a "mountain", and said pieces curving, there's no doubt that the sprite would touch the "rectangle".

What I need is something to trigger when the sprite hits the actual wall, however my limited knowledge of Objective-C isn't helping my case.

I imagine someone out there will know what I can do to resolve this, as for all I know it could be a simple solution.

Thank you in advance everyone!

Upvotes: 1

Views: 168

Answers (1)

Rob Napier
Rob Napier

Reputation: 299275

First, I'd probably not build these basic pieces yourself. For iOS 7, you can use SpriteKit, which is built-in. If you want to support older versions of iOS, look at cocos2d (it's good for iOS 7, too).

But to the question, one approach for detecting arbitrary overlaps is to draw both objects into a buffer and check if there are any overlapping pixels (for instance, by drawing one in in pure red, and another in pure green, and then looking for pixels that have both). For a discussion of how to do this kind of thing in Core Graphics, see Clipping a CGRect to a CGPath, which provides sample code for the simplest version (checking for the intersection of a rectangle and curve), but the same approach can be used more generally. Note that this drawing can get expensive if you're doing it constantly, so usually you first check whether the bounding rectangles overlap. That tells you whether it's even worth the trouble to look closer.

But first I'd look at SpriteKit.

Upvotes: 2

Related Questions