Search code examples
iphoneioscocos2d-iphoneccsprite

How to detect collision of sprite in cocos2d


i want to detect collision of a sprite with another sprite. but i want to check whether the sprite is touched with left part of other sprite or touched with right part of sprite. i am using below code for detecting collision. but this detect the overall collision(sprite touched to at any point of other sprite). but want to count is as collision if the sprite is touched to front side of other sprite.

if (CGRectIntersectsRect(sprite1.boundingBox, sprite2.boundingBox)) {
            NSLog(@"sprite1 to delete");
 }

any one know how to do this?


Solution

  • Would you be able to compare the positions of the sprites at the time of collision?

    Assume sprite1.anchorpoint, sprite2.anchorpoint = ccp(0,0). At time when collision is detected:

    // left part of sprite 1 touched right part of sprite 2
    if (sprite1.position.x == sprite2.position.x + sprite2.contentSize.width.x) {
    
    }
    // right part of sprite 1 touched left part of sprite 2
    else if (sprite1.position.x + sprite1.contentSize.width.x == sprite2.position.x) {
    
    }