2

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.

Shalin Shah
  • 8,145
  • 6
  • 31
  • 44

2 Answers2

4

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.

Dobroćudni Tapir
  • 3,082
  • 20
  • 37
  • Thanks! This worked perfectly! Also, i think you forgot a parenthesis after `[spriteTwo boundingBox]`. – Shalin Shah Nov 25 '13 at 08:18
  • 2
    This will return TRUE when the circle's bounding box is within the rectangle's, not the circle itself. see: http://www.pixentral.com/pics/1UsZAiYadMHwyToj3ruWOKms2gAAb0.png – erkanyildiz Nov 25 '13 at 08:34
  • That is true, but as i said it is not pixel perfect but merely good enough for this case, and most game situations – Dobroćudni Tapir Nov 25 '13 at 08:46
0

This is not a solution for those who use Cocos2d-ObjC, but will help for Cocos2d-x devs (for instance, personally I found this topic because was searching for the same for my c++ game).

Cocos2d-x has method "intersectsCircle" for Rect class.

Here is how I solved in my c++ project almost the same problem as one described by you:

bool ObstacleEntity::hasCollisionAgainst(cocos2d::Sprite *spr)
{
    cocos2d::Rect rect = cocos2d::Rect( spr->getPositionX(), spr->getPositionY(), spr->getBoundingBox().size.width, spr->getBoundingBox().size.height);

    float rw = this->getBoundingBox().size.width / 2;
    float rh = this->getBoundingBox().size.height / 2;

    float radius = ( rw > rh ) ? rw : rh;
    cocos2d::Vec2 center( this->getPositionX() + rw, this->getPositionY() + rh );

    return rect.intersectsCircle( center, radius );
}

Passed Sprite here is rectangle, while ObstacleEntity always is almost ideally round. Note that anchor points for all entities are set to lower left corner in my case.

George Keeper
  • 445
  • 5
  • 11