Swift – Spritekit:当节点触及底部边缘时,添加一个计数器(高分计算器)

我有我的代码设置,以便当我的球节点触摸屏幕的底部边缘程序检测到它。 我想要的是,每当它触及底部边缘,本质上是一个高分variables,一个variables增加1。

我到目前为止,但它只打印“你的分数是1”。 每次节点都触及底部边界。 任何帮助,将不胜感激。 干杯!

我的代码:

func didBeginContact(contact: SKPhysicsContact) { // 1. Create local variables for two physics bodies var firstBody: SKPhysicsBody var secondBody: SKPhysicsBody var counter = Int() // 2. Assign the two physics bodies so that the one with the lower category is always stored in firstBody if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask { firstBody = contact.bodyA secondBody = contact.bodyB } else { firstBody = contact.bodyB secondBody = contact.bodyA } // 3. react to the contact between ball and bottom if firstBody.categoryBitMask == BallCategory && secondBody.categoryBitMask == BottomCategory { counter++ println("Score is \(counter).") } 

问题是,你在函数didBeginContact声明了variables计数器。 所以每次调用该函数时,都会创build一个新的variablescounter

声明并初始化函数以外的计数器。 最好的将在一个单身分谱:

 class Scoresheet { // Singleton static let sharedInstance = Scoresheet() var scoreCounter = 0 } 

增加值: Scoresheet.sharedInstance.scoreCounter++

你的代码是正确的,因为在任何SKSpriteNode触摸调用这个函数

 func didBeginContact(contact: SKPhysicsContact) 

但是你需要增加你的分数

  if firstBody.categoryBitMask == BallCategory && secondBody.categoryBitMask == BottomCategory { //TODO: Replace the log statement with display of Game Over Scene counter ++ println("Score is \(counter).") } 

尝试这可能是有益的..谢谢