Swift - Spritekit:当节点触及底边

时间:2015-05-16 04:49:43

标签: ios css node.js swift

我有我的代码设置,以便当我的球节点触及屏幕的下边缘时,程序会检测到它。我想要的是,每当触及底边时,var就会增加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).")
    }

2 个答案:

答案 0 :(得分:1)

问题是,你在函数didBeginContact中声明了变量counter。因此,每次调用函数时,都会创建一个新变量counter

在函数外声明并初始化计数器。最好是在单身分数表中:

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

增加价值: Scoresheet.sharedInstance.scoreCounter++

答案 1 :(得分:0)

您的代码是正确的,因为在任何 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).")
}

试试这可能会有所帮助..谢谢