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

176 Views Asked by At

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?

3

There are 3 best solutions below

0
On BEST ANSWER

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];
}
2
On

If your bonus is meant for 2 simultaneous contacts, check out the clean and sexy-sounding -(NSArray *)allContactedBodies instance method that you can call on your physicsBody. It returns an array of all other physics bodies it's currently in contact with. Just remember to set the contact bitmasks appropriately.

0
On

Maybe you can store the #hits in an property and kick of method that checks the number of hits after x seconds of an initial hit?

In other words: separate the hit detection from the bonus logic.