当两个节点发生碰撞时结束游戏

时间:2015-12-07 17:06:38

标签: swift sprite-kit skphysicsbody skscene

我有两个独立的节点和他们自己的物理体,当它们发生碰撞时,一个带有高分和重放按钮的SKScene应该出现。这就是我的场景:

func didBeginContact(contact: SKPhysicsContact) {
  gameOver()

    print("gameOver")
}

这就是我的节点物理机构的设置方式:

   func createDown(position: CGPoint) -> SKNode {
    let circleNode = SKSpriteNode()
    let circle = SKSpriteNode(imageNamed: "first@2x")
    circleNode.position = CGPointMake(position.x, position.y)
    circleNode.physicsBody = SKPhysicsBody(circleOfRadius: 30)
    circleNode.physicsBody?.dynamic = false
    circle.size = CGSize(width: 75, height: 75)
    circleNode.addChild(circle)
    circleNode.name = "circleNode"
    circle.name = "CIRCLE"
    let up = SKAction.moveByX(0, y: -9000, duration: 100)
     physicsBody?.categoryBitMask = blackCategory
    circleNode.runAction(up)
    return circleNode
}
func playerPhysics() {
player.physicsBody = SKPhysicsBody(circleOfRadius: 30)
    player.physicsBody?.affectedByGravity = false
  player.physicsBody?.categoryBitMask = playerCategory
     player.physicsBody?.contactTestBitMask = blackCategory
}

这是我的gameOver功能:

 func gameOver() {
   gameEnd = true
     let reveal = SKTransition.fadeWithDuration(1)
     let scene = GameOver(size: self.scene!.size)
     view!.presentScene(scene, transition: reveal)


}

我错过了什么吗?如有必要,将发布更多代码。

2 个答案:

答案 0 :(得分:0)

当两个节点发生碰撞时,只需使用intersectsNode并调用gameOver()。

if yourNode.intersectsNode(yourSecondNode) { gameOver() }

SKNode类参考:SKNode

答案 1 :(得分:-1)

You need to add the physics world as a contact delegate for your methods to work.

class GameScene: SKScene, SKPhysicsContactDelegate {

    override func didMoveToView(view: SKView) {
        physicsWorld.contactDelegate = self

And like Whirlwind said, you need to set your categoryBitMask and contactTestBitMask for the circle node.

Then everything should work. I hope I could help.