Using CGRectIntersectsRect for collision detection
I've got a long rectangular image which is rotated at different kind of angles. However the frame of the rectangular image does not rotate along with the image and instead, the rotation causes the frame to to become larger to fit the rotated image. So when I used CGRectIntersectsRect, the collision detection is totally off because the other image colliding with the rectangular image will collide before it even reaches the visible area of the rect image. In case you don't really know what I'm talking about, have a look at the ascii drawing:
normal rectangular image frame, O -> pixels, |, – -> frame
|----------|
|OOOOOOOOOO|
|----------|
after rotation
|----------|
|O |
| O |
| O |
| O |
| O |
| O |
| O |
| O |
| O |
|----------|
I've read through some of the collision articles开发者_JS百科 but all of them are talking about collision with a normal straight rectangle and what I really want is collision with a slanted image, preferably pixel collision detection. TIA for any suggestions made.
If you're on the mac, you can use -[NSImage hitTestRect:withImageDestinationRect:context:hints:flipped:]
to decide if a particular rectangle intersects non-transparent pixels in your image. See the header comment for usage.
You can’t use the frame
property of UIView
to do collisions on rotated objects, as the frame
is no longer valid as soon as you start transforming the view. You need to come up with some custom solution. What exactly that will be depends on many things, especially performance.
You can create a geometric collision envelope for the image, a polygon you can rotate along with the image. Or you can use pixel-perfect collision detection combined with simple bounds-checking to avoid the expensive pixel-check when possible. And, if you really wanted to get fancy, you can resort to some full-featured physics simulator such as Box2D.
If you want better advice, give us more detail. How often do you need to check for the collisions? Once? 40 times per second?
精彩评论