views:

396

answers:

2

Hi guys,

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 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.

A: 

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.

Ken
I found it in the documentation but I can't seem to use it.my auto complete sentence stops at hitTest and there is no hitTestRect. googled it too but returns no useful information on it
A: 

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?

zoul
I dun really have any more details i can give you now. my main aim here is to detect collision between an CGrect and a rotated rectangular image. Since CGRectIntersectRect wouldn't work in this case, I'll have to take a look at your suggestions