Search code examples
iphonecocos2d-iphonecollision-detection

cocos-2d collision detection with a rect and falling objects


I've got a player sprite that I can move around on the screen using the accelerometer. Now I want to check if it collides with any of the many randomly falling objects I've created. I know about the CGRectIntersectsRect function, but I don't want to have to know the other object's name. Is there some kind of getElementAt function like in Java, that I can continue to check if there is any object overlapping with my player?

Thanks in advance!


Solution

  • The only cocos2d equivalent to getElementAt I know of is getChildByTag:. Alternatively You can loop through every child of the layer using:

    for (CCNode *child in [self children]) {
        if (CGRectIntersects(child.boundingBox, player.boundingBox) {
            // perform collision stuff    
        }
    }
    

    Also important to remember is that this is horribly inefficient, particularly with many objects. You might consider using a physics engine to perform the efficient collision detection for you.