0
func didBegin(_ contact: SKPhysicsContact) {
    // Each contact has two bodies, but we do not know which two bodies
    // first we will find the player body, and then use the other body to determine the contact type
    let otherBody: SKPhysicsBody
    // combine the two player physics categories into one bitmask using the bitwise OR operator
    let playerMask = PhysicsCategory.player.rawValue | PhysicsCategory.damagedPlayer.rawValue
    // Use the bitwise AND operator to find the penguin.
    // This returns a positive number if body A's category is the same as either the player or damaged player
    if contact.bodyA.categoryBitMask & playerMask > 0 {
        // body A is the player, so we test body B
        otherBody = contact.bodyB
    }
    else {
        // body B is the player, so we test body A
        otherBody = contact.bodyA
    }
    
    // Determine the type of contact
    switch otherBody.categoryBitMask {
    case PhysicsCategory.ground.rawValue:
        print("hit the ground")
    case PhysicsCategory.enemy.rawValue:
        print("hit enemy, take damage")
    case PhysicsCategory.coin.rawValue:
        print("collect a coin, more wealthy")
    case PhysicsCategory.powerup.rawValue:
        print("gained a power up")
    default:
        print("Contact with no game logic")
    
    }
    
}

I am trying to detect collisions properly. Whenever my player hits another object, the console is recording multiple collisions instead of a single collision. So I was wondering if there was any way of fixing this.

AMara
  • 23
  • 3

1 Answers1

0

I assume that you are getting multiple messages from your didBegin for what seems to be a single collision?

didBegin(Contact:) appears to be called for every contact point between 2 nodes, not just for a single contact. You can't prevent multiple calls to didBegin(contact:) so you have to code your contact processing to take this into account.

One way is to use the userData field (https://developer.apple.com/documentation/spritekit/sknode/1483121-userdata) on a node to flag that contact processing has already occurred but it really depends on what you want to happen when the nodes contact, be it increasing a score, decreasing an armour value, removing anode from the scene etc.

See this answer which links to further discussions : https://stackoverflow.com/a/43064543/1430420

Steve Ives
  • 7,894
  • 3
  • 24
  • 55