0
votes

I follow the simple collision detection method of using the bounding box method, and checking whether they intersect.

The code is as follows:

CCRect projectileRect = projectileSprite->boundingBox();      
CCRect enemyRect = enemySprite->boundingBox();

if (projectileRect.intersectsRect(enemyRect)) {
    // do stuff
}

EDIT: I tried creating my own bounding box as well by getting the x, y positions and adding the width and height of the sprite.

Now, a funny thing happens is that is the collision detection works, but it works a bit incorrectly. The collision detection gets detected, before the actual intersection takes place.

I verified this by switching on CC_SPRITE_DEBUG_DRAW and it indeed takes place a few moments before the collision happens, i.e. the projectile's bounding box is outside the enemy's bounding box.

This seems to be a basic functionality that most folks recommend, and I seemed to be missing something. Can anyone deduce, what I could possibly be doing wrong?

PS: I verified this with cocos2d-x-2.2 and cocos2d-2.1rc0-x-2.1.3.

PPS: On a side note, I tried to draw my own bounding box using ccDrawSolidRect, but I can't seem to get that working.

2

2 Answers

0
votes

boundingBox() just gives you the bounds/rect of the node irrespective of its location/position on parent node. You need to translate it according to its position like this:

CCSize = projectileSprite->getContentSize();
CCRect projectileRect = CCRectMake(
    projectileSprite->getPosition().x - (size.width/2),
    projectileSprite->getPosition().y - (size.height/2),
    size.width,
    size.height);

size = enemySprite->getContentSize();
CCRect enemyRect = CCRectMake(
    enemySprite->getPosition().x - (size.width/2),
    enemySprite->getPosition().y - (size.height/2),
    size.width,
    size.height);

if (projectileRect.intersectsRect(enemyRect)) {
    // Collision detected
}
0
votes

I believe I found the answer through the old 'walk through your code with printfs(CCLogs) and checking the framework code' method. :)

I believe this is a limitation of the intersectRect method. What happens is that my projectile sprite is rotated. Now, when a sprite is rotated, you will notice that, that max X, and the max Y are not in the same coordinate. One possible combination would be (min X, max Y), (min Y, max X).

The intersectRect does not take into account of this possibility, and assumes a rect will always be parallel to the X and Y axises, which is not the case in my scenario.

Hope this helps someone. I will post a solution, after I write out a simple method to tackle this.