Search code examples
swiftcollisioncontacts

Swift SpriteKit Setting up collisions/contact bitmasks with 3 nodes


I have several collisions set up working perfectly in my app however I cannot for the life of me get the final 2 collisions to work on the same node.

Here is what I have:

alien.physicsBody!.contactTestBitMask = ColliderType.object.rawValue
alien.physicsBody!.categoryBitMask = ColliderType.object.rawValue | ColliderType.torp.rawValue
alien.physicsBody!.collisionBitMask = ColliderType.object.rawValue

ship.physicsBody!.contactTestBitMask = ColliderType.ship.rawValue | ColliderType.object.rawValue
ship.physicsBody!.categoryBitMask = ColliderType.ship.rawValue
ship.physicsBody!.collisionBitMask = ColliderType.ship.rawValue


torpedoNode.physicsBody!.contactTestBitMask = ColliderType.torp.rawValue
torpedoNode.physicsBody!.categoryBitMask = ColliderType.torp.rawValue
torpedoNode.physicsBody!.collisionBitMask = ColliderType.torp.rawValue

As the code is above, the torp contacts with the alien. However, the ship does not contact the alien.

If I remove "ColliderType.torp.rawValue" from the alien categoryBitMask then the ship DOES contact the alien but then the torp DOESN'T contact the ship.

For the ship to contact alien I use:

if contact.bodyA.categoryBitMask == ColliderType.object.rawValue || contact.bodyB.categoryBitMask == ColliderType.object.rawValue

And for the torp to contact the alien I use:

if contact.bodyA.categoryBitMask == ColliderType.torp.rawValue || contact.bodyB.categoryBitMask == ColliderType.torp.rawValue {

How can I get BOTH to work?! I've spent days and just can't get my head around it.

I can get either to work perfectly just not both together.


Solution

  • For anyone having the same problem, in this case @Alex Ingram wanted the alien to collide with both the ship and the torpedo, here is the solution that helped him.

    alien.physicsBody!.contactTestBitMask = ColliderType.ship.rawValue | ColliderType.torp.rawValue
    alien.physicsBody!.categoryBitMask = ColliderType.object.rawValue //Im assuming this is his alien's BitMask
    alien.physicsBody!.collisionBitMask = none
    

    Then, in didBeginContact he had to write the following

     //alien contacting the torpedo
    if contact.bodyA.categoryBitMask == ColliderType.object.rawValue && contact.bodyB.categoryBitMask == ColliderType.torp.rawValue{
       //then do the following
       }
     //alien contacting the ship
    if contact.bodyA.categoryBitMask == ColliderType.object.rawValue && contact.bodyB.categoryBitMask == ColliderType.ship.rawValue{
           //then do the following
           }