Search code examples
swiftsprite-kitcollisioncategoriesskspritenode

prevent Spritekit nodes with the same Catagorymask from colliding


I have this Spritekit project that I am working on where there is a player node that you move around the screen and then there are bullet nodes that shoot at you. My problem is that not only do the bullets hit the player, but they also hit each other. I have given the player and the bullets their own category/collision/contact masks.

I specify all the different category masks here(some of them can be ignored):

enum CategoryMask : UInt32 {
    case playeragain = 11
    case player = 1
    case GBullet = 2
    case BBullet = 3
    case enemyships = 4
    case coin = 5
    case boss = 6
}

BBullet is the bullets that are shot at you and player is the node that the user controls.

I then assign these masks to each node:

    player.physicsBody?.categoryBitMask = CategoryMask.player.rawValue
    player.physicsBody?.collisionBitMask = CategoryMask.BBullet.rawValue | CategoryMask.coin.rawValue
    player.physicsBody?.contactTestBitMask = CategoryMask.BBullet.rawValue | CategoryMask.coin.rawValue


    bullet.physicsBody?.categoryBitMask = CategoryMask.BBullet.rawValue
    bullet.physicsBody?.collisionBitMask = CategoryMask.player.rawValue
    bullet.physicsBody?.contactTestBitMask = CategoryMask.player.rawValue

The collision between the bullets and the player works fine and I have set up how to handle each collision in the "Did begin contact" function. I would like to specify that I don't want the bullets to collide with each other.


Solution

  • It's bit mask in binary.

    So it's better to use some bit operator:

    enum CategoryMask : UInt32 {
    case playeragain = 0b00000001
    case player = 0b00000010
    case GBullet = 0b00000100
    case BBullet = 0b00001000
    case enemyships = 0b00010000
    case coin = 0b00100000
    case boss = 0b01000000
      }
    
    
    
       // case playeragain = 1<<0 //1
       // case player = 1<<1    // 2
        // case GBullet = 1<<2  // 4
       // case BBullet = 1<<3   //8
       // case enemyships = 1<<4 //16
       // case coin = 1<<5 //32
       // case boss = 1<<6 //64
    
      //
    

    This should give you what you really what.

    It's an example from Apple Document and redball will hit ground and blue ball will not.

        let ground = SKShapeNode()
    
          redBall.physicsBody?.collisionBitMask = 0b0001
          blueBall.physicsBody?.collisionBitMask = 0b0010
          ground.physicsBody?.categoryBitMask = 0b0001