swiftsprite-kitgamekit

Swift - How to add scene boundaries for specific nodes?


I'm trying to develop an IOS game using SpriteKit, and I want to add a Physics body to the scene so that the player won't be able to go through the edges of the screen. At the same time, I want some nodes (for example - bombs that fall from the sky) to be able to go through the edges of the screen.

I know that I can use the following line to add a physics body to the scene:

self.physicsBody = SKPhysicsBody (edgeLoopFrom: self.frame)

My question is how can I allow a "bomb" object to go through such body while having a "player" object obligated to those boundaries.


Solution

  • The answer is relative to categoryBitMask and collisionBitMask of the involved physic bodies.

    For example, for the scene:

    if let scenePB = scene.physicsBody {
        scenePB.categoryBitMask = 1
        scenePB.collisionBitMask = 2 // collides with player
    }
    

    For the player:

    if let playerPB = player.physicsBody {
        playerPB.categoryBitMask = 2
        playerPB.collisionBitMask = 1+4 // collides with scene and bombs
    }
    

    For any bomb:

    if let bombPB = bomb.physicsBody {
        bombPB.categoryBitMask = 4
        bombPB.collisionBitMask = 2 // collides with player
    }