Shalin Shah Shalin Shah - 1 year ago 85
iOS Question

Rectangle and Circle collision detection

I am trying to do collision detection between a rectangle and a circle. I came up with this method:

-(BOOL) isCollidingRect:(CCSprite *) spriteOne WithSphere:(CCSprite *) spriteTwo {
float diff = ccpDistance(spriteOne.position, spriteTwo.position);
float obj1Radii = [spriteOne boundingBox].size.width/2;
float obj2Radii = [spriteTwo boundingBox].size.width/2;
if (diff < obj1Radii + obj2Radii) {
return YES;
} else {
return NO;

and this is how I check it:

if ([self isCollidingRect:player WithSphere:blocker] == true) {
[self playerdeathstart];

This seems to work properly on the side of the rectangle but it doesn't above or below it. On the top and bottom, the collision occurs too early.

Kinda Like this..

Is there a way I can get this collision to detected properly? Thank you for your help.

Answer Source

You can use CGRectIntersectsRect to achieve this.

-(BOOL) isCollidingRect:(CCSprite *) spriteOne WithSphere:(CCSprite *) spriteTwo {
    return CGRectIntersectsRect([spriteOne boundingBox],[spriteTwo boundingBox]);

It is not pixel perfect but as i understand that is not necessary in this case.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download