Search code examples
objective-cios7sprite-kitskphysicsworld

How to detect number of nodes involved in a collision in SpriteKit


I am creating a shooting game where I am shooting projectiles from one node targeted at enemy projectiles. When the projectile makes contact with two enemy nodes simultaneously, the contact delegate gets called twice. I want to be able to know how many nodes the projectile has come in contact with in order to give the player a 2x bonus.

Can anybody suggest a clean and efficient way to achieve this?


Solution

  • So, I went with the suggestion by Dobroćudni Tapir in the comments section.

    Added a variable called hitCount as a property of the subclassed projectile SKSpriteNode.

    @property NSUInteger hitCount;
    

    Then in the didBeginContact of the scene

    -(void)didBeginContact:(SKPhysicsContact *)contact
    {
        SKNode *firstBody;
        SKNode *secondBody;
    if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask)
        {
            firstBody = contact.bodyA.node;
            secondBody = contact.bodyB.node;
        }
        else
        {
            firstBody = contact.bodyB.node;
            secondBody = contact.bodyA.node;
        }
    
        if (firstBody.physicsBody.categoryBitMask == projectileCategory && secondBody.physicsBody.categoryBitMask == delusionCategory)
        {
            //Other logic
    
            RCCProjectile *projectile = (RCCProjectile*)firstBody;
            projectile.hitcount ++;
            [projectile removeFromParent];
        }
    }
    

    Then, finally in the projectileNode, I overrode the removeFromParent method

    -(void)removeFromParent
    {
        if (self.hitcount >= 2)
        {
            [(LevelScene*)self.scene showBonusForProjectile:self];
        }
    
        [super removeFromParent];
    }