didBegin Contact doesn't work

时间:2016-10-20 18:34:00

标签: ios swift sprite-kit swift3

I am trying to end the game once the user ("Hero") gets hit by a falling SKSpriteNode ("GameOver"). When the contact occurs, nothing happens. My code is below.

func didBegin(_ contact: SKPhysicsContact) {

    let firstBody = contact.bodyA
    let secondBody = contact.bodyB

    if firstBody.categoryBitMask == PhysicsCategory.GameOver && secondBody.categoryBitMask == PhysicsCategory.Hero {

        secondBody.node?.removeFromParent()

    }

    else if firstBody.categoryBitMask == PhysicsCategory.Hero && secondBody.categoryBitMask == PhysicsCategory.GameOver {

        firstBody.node?.removeFromParent()

    }
}

Here is where I set up the Hero physicsbody:

    hero.physicsBody = SKPhysicsBody(rectangleOf: hero.size)
    hero.physicsBody?.categoryBitMask = PhysicsCategory.Hero
    hero.physicsBody?.contactTestBitMask = PhysicsCategory.GameOver
    hero.physicsBody?.collisionBitMask = PhysicsCategory.Ground | PhysicsCategory.Wall | PhysicsCategory.GameOver
    hero.physicsBody?.allowsRotation = false
    hero.physicsBody?.affectedByGravity = true
    hero.physicsBody?.isDynamic = true

Here is where I set up the PhysicsBody of "GameOver":

    gameOverNode.physicsBody = SKPhysicsBody(rectangleOf: gameOverNode.size)
    gameOverNode.physicsBody?.categoryBitMask = PhysicsCategory.GameOver
    gameOverNode.physicsBody?.contactTestBitMask = PhysicsCategory.Hero
    gameOverNode.physicsBody?.collisionBitMask = 0
    gameOverNode.physicsBody?.affectedByGravity = true
    gameOverNode.physicsBody?.isDynamic = true

0 个答案:

没有答案