iosswiftsprite-kitskphysicscontact

SpriteKit: How to prevent two SKSpriteNodes from colliding (in Swift)


I am making a relatively simple game consisting of a player, obstacles, and coins. My goal is to have collisions between the obstacles and the player only, and for contact between the player and a coin to trigger didBeginContact.

Here's some code:

//declare categoryBitMasks
struct physicsCategories {
    static let playerCategory : UInt32 = 1
    static let coinCategory: UInt32 = 2
    static let obstacleCategory : UInt32 = 3 
}

//assign physics categories 
playerNode!.physicsBody?.categoryBitMask = physicsCategories.playerCategory
playerNode!.physicsBody?.collisionBitMask = physicsCategories.obstacleCategory
playerNode!.physicsBody?.contactTestBitMask = physicsCategories.coinCategory


obstacleNode.physicsBody?.categoryBitMask = physicsCategories.obstacleCategory
obstacleNode.physicsBody?.collisionBitMask = physicsCategories.playerCategory
obstacleNode.physicsBody?.contactTestBitMask = 0


coinNode.physicsBody?.categoryBitMask = physicsCategories.coinCategory
coinNode.physicsBody?.collisionBitMask = 0
coinNode.physicsBody?.contactTestBitMask = physicsCategories.playerCategory

The didBeginContact function removes the coin from the view and adds one to the users currency bank. This function calls when the player hits the coin, but a collision occurs before the coin is removed. The collision is very disruptive of the gameplay and I have been unable to find a working solution. Any suggestions?


Solution

  • Your problem is your categories, search how bit masks work. You can't do 1,2,3 they have to be powers of 2; 0x1 << 0, 0x1 << 1, 0x1 << 2 etc