SWIFT:如果“didBeginContact”函数中的语句运行太多次

时间:2015-08-18 19:24:41

标签: ios swift if-statement sprite-kit

我的问题是,其中包含scoreUpOne()的if语句会运行太多次,即使弹丸只击中evilFlappy一次。 这是我的代码:

func scoreUpOne() {
    if scoreUp == true{
        scoreLabel = scoreLabel++
        myScene.scoreLabel.text = "\(scoreLabel)"
        scoreUp = false
    }
}


func evilFlappyRespawnTimer(timer : NSTimer){
    evilFlappy.position = CGPointMake(940, 320)
    evilFlappy.hidden = false
}


func didBeginContact(contact: SKPhysicsContact) {
    if (contact.bodyA.node?.name == "projectile" && contact.bodyB.node?.name == "bottomBolt"){
        projectile.hidden = true
    }else if (contact.bodyA.node?.name == "projectile" && contact.bodyB.node?.name == "topBolt"){
        projectile.hidden = true
    }else if (contact.bodyA.node?.name == "topBolt" && contact.bodyB.node?.name == "projectile"){
        projectile.hidden = true
    }else if (contact.bodyA.node?.name == "bottomBolt" && contact.bodyB.node?.name == "projectile"){
        projectile.hidden = true


    }

    if (contact.bodyA.node?.name == "projectile" && contact.bodyB.node?.name == "evilFlappy") {
        projectile.hidden = true
        evilFlappy.hidden = true


        scoreUp = true
        scoreUpOne()
        NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: "evilFlappyRespawnTimer:", userInfo: nil, repeats: false)

    }
    else if (contact.bodyA.node?.name == "evilFlappy" && contact.bodyB.node?.name == "projectile"){

        evilFlappy.hidden = true
        projectile.hidden = true
        scoreUp = true
        scoreUpOne()
        NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: "evilFlappyRespawnTimer:", userInfo: nil, repeats: false)


    }
    if (contact.bodyA.node?.name == "flappy" && contact.bodyB.node?.name == "sprite") {
        gameOver()
    }
    else if  (contact.bodyA.node?.name == "sprite" && contact.bodyB.node?.name == "flappy") {
        gameOver()
    }

问题是这些if语句运行次数过多,导致分数上升超过一个点:

if (contact.bodyA.node?.name == "projectile" && contact.bodyB.node?.name == "evilFlappy") {
    projectile.hidden = true
    evilFlappy.hidden = true


    scoreUp = true
    scoreUpOne()
    NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: "evilFlappyRespawnTimer:", userInfo: nil, repeats: false)

}
else if (contact.bodyA.node?.name == "evilFlappy" && contact.bodyB.node?.name == "projectile"){

    evilFlappy.hidden = true
    projectile.hidden = true
    scoreUp = true
    scoreUpOne()
    NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: "evilFlappyRespawnTimer:", userInfo: nil, repeats: false)


}

每次射弹击中邪恶的飞行物时,我怎么能让得分只上升一点?

任何建议都将不胜感激。感谢。

1 个答案:

答案 0 :(得分:0)

为什么你甚至使用scoreUp?这种条件没有理由。

如果分数增加,请更新UI。您可以在乐谱变量上设置键值观察(KVO),以查看它何时更新并相应地更新UI。或者,您可以在分数更新后发布通知,您的视图可以监听并更新。