I figured out how to get func didBeginContact(contact: SKPhysicsContact) only once. This allows physical bodies with the SKPhysicsBody(texture: size:) count collisions once, even if in reality (due to the nature of the physical texture body) this function will be called several times.
Step 1:
Create a name property for SKSpriteNode (in this example we will use the ball) and set it to a unique name. We can do this by creating int
var number = 0 ball.name = "ball \(number)"
This allows you to create a unique evertime name that creates the object.
Step 2:
Create an array to store them, add a ball to the array, increase the number
var array: [String] = [] var number = 0 ball.name = "ball \(number)" array.append(ball.name!) number ++
Step 3: Now in func didBeginContact(contact: SKPhysicsContact) find if the name is in the array. If it increases the score, remove the node and remove the name from the array. If the name is not in the array, do nothing.
Removing the name from the array allows us to only count the function call once.
func didBeginContact(contact: SKPhysicsContact) { if ( contact.bodyA.categoryBitMask & BodyType.shield.rawValue ) == BodyType.shield.rawValue { var name = contact.bodyB.node?.name! let index = find(array, name!) if contains(array, name!) { score++ contact.bodyB.node?.removeFromParent() array.removeAtIndex(index!) } } }
source share