Dean Sponholz Dean Sponholz - 6 months ago 12
Swift Question

Why is my didBeginContact function detecting way too many collisions?

My didBeginContact function is detecting about 60 collisions between two SKSpriteNodes when there should only be one.

func didBeginContact(contact: SKPhysicsContact) {
let firstBody = contact.bodyA
let secondBody = contact.bodyB
if firstBody.categoryBitMask == bulletCategory && secondBody.categoryBitMask == dragonCategory || firstBody.categoryBitMask == dragonCategory && secondBody.categoryBitMask == bulletCategory{

print("collision happened")

When the nodes come into contact the console prints "collision happened" many many times.

Here is how i declare physics bodys for each SKSpriteNode

dragonNode.physicsBody = SKPhysicsBody(texture: dragonNode.texture!, size: CGSizeMake(dragonNode.size.width, dragonNode.size.height))
dragonNode.physicsBody?.affectedByGravity = false
dragonNode.physicsBody?.dynamic = true
dragonNode.physicsBody?.categoryBitMask = dragonCategory
dragonNode.physicsBody?.collisionBitMask = bulletCategory
dragonNode.physicsBody?.contactTestBitMask = bulletCategory

bulletNode.physicsBody = SKPhysicsBody(texture: texture, size: texture.size())
bulletNode.physicsBody?.affectedByGravity = false
bulletNode.physicsBody?.dynamic = true
bulletNode.physicsBody?.categoryBitMask = bulletCategory
bulletNode.physicsBody?.collisionBitMask = dragonCategory
bulletNode.physicsBody?.contactTestBitMask = dragonCategory

This is one of the last things i need to fix for my game to be completed so if anyone can help that would be great!


It's because theoretically your game is running at 60 frames per second. So every 60th of a second it is detecting the collision and printing the warning. You haven't put any code into say stop detecting this collision. You could always put a flag on the object

dragonNode.collided = true

and then detect for the collision and the flag

if (firstBody.categoryBitMask == bulletCategory && secondBody.categoryBitMask == dragonCategory || firstBody.categoryBitMask == dragonCategory && secondBody.categoryBitMask == bulletCategory) && dragonNode.collided != true {
    dragonNode.collided = true
    print("collision happened")

this way the collision only fires once