-1
CGRect rect4 = CGRectMake(rock.position.x, rock.position.y, rock.size.width, rock.size.height);
CGRect bulletRect = CGRectMake(bullet.position.x, bullet.position.y, bullet.size.width, bullet.size.height);
if (CGRectIntersectsRect(bulletRect, rect4)) {
    NSLog(@"hit Bullet");
    //[bullet removeFromParent];
}

It seems to "Hit the Bullet" even if the rect 4 is no where near the bullet. Thank you

CodeSmile
  • 64,284
  • 20
  • 132
  • 217
  • We need more information. Is the bullet and the rock in the same coordinate system (node)? How does the bullet and the rock look like? – yinkou Jan 29 '14 at 12:16
  • 1
    The rock is not a perfect box shape but is an irregular polygon shape – user3208783 Jan 29 '14 at 14:52

1 Answers1

0

I don't know exactly how your shapes look like, but my guess is that their are only loosly symbolized by a rectangle.

-First check that your x and y rock and bullet positions are really their upper left corner coordinates, if not consider a translation of your bounding rectangle.

-To increase the precision of the bounding shape, without getting too complicated you could use a cloud of points that are situated on the boarder of the less rectangular of your object. Then you would use CGRectContainsPoint to check if the shapes intersect. You should position your points on the most prominent part of the polygon boarder. You could get their coordinate relatively to the rock.position.x and y coordinates.

For example: you know your rock's x and y. You can situate a point with something like: p1 = x+dx, y+dy.

enter image description here

Note that here, in the case where there is no intersection, a typical bounding box approach would have considered it an intersection.

So, in code:

CGPoint p1 = CGPointMake(rock.position.x+dx, rock.position.y+dy);
CGRect bulletRect = CGRectMake(bullet.position.x, bullet.position.y, bullet.size.width, bullet.size.height);
if (CGRectContainsPoint(bulletRect, p1)) {
    NSLog(@"hit Bullet");
}

Of course, the more points you have, the more precise it will be. Just loop over a point array and break if you have a true.

Another option, much more complicated and accurate, could be a graphic engine such as Box2D

Hope it helped.

F


EDIT


Dx and Dy are the differences between your known point (rock.position.x, rock.position.y) and the point to test (p1 here).

dx and dy

Legisey
  • 503
  • 1
  • 4
  • 18