当屏幕被触摸时,我该如何结束游戏?

When the screen is touched, how do I make the game over?

我想要一个游戏结束屏幕,并且在特定动画期间触摸屏幕时游戏停止。

    let lightTexture = SKTexture(imageNamed: "green light.png")
    let lightTexture2 = SKTexture(imageNamed: "red light.png")

    let animateGreenLight = SKAction.sequence([SKAction.waitForDuration(2.0, withRange: 0.1),   SKAction.animateWithTextures([lightTexture, lightTexture2], timePerFrame: 3)])
    let changeGreenLight = SKAction.repeatActionForever(animateGreenLight)


    let animateRedLight = SKAction.sequence([SKAction.waitForDuration(2.0, withRange: 0.1), SKAction.animateWithTextures([lightTexture, lightTexture2], timePerFrame: 3)])
    let changeRedLight = SKAction.repeatActionForever(animateRedLight)


    let greenLight = SKSpriteNode(texture: lightTexture)
    greenLight.position = CGPointMake(CGRectGetMidX(self.frame), 650)
    greenLight.runAction(changeGreenLight)

    self.addChild(greenLight)

    let redLight = SKSpriteNode(texture: lightTexture2)
    redLight.position = CGPointMake(CGRectGetMidX(self.frame), 650)
    redLight.runAction(changeRedLight)

    self.addChild(redLight)

当红灯动画出现在屏幕上时,我希望游戏结束。我是否必须做一个 if 语句,如果是的话具体是为了什么?

提前致谢!

您可以自己制作另一个与红灯具有相同大小和位置的节点。此外,该节点能够处理触摸事件。然后,在动画运行之前添加该节点。这可以通过一系列操作来完成,例如:

let addAction = SKAction.runBlock({ self.addChild(touchNode) })
let animationAction = SKAction.repeatActionForever(animateRedLight)

redLight.runAction(SKAction.sequence([ addAction, animationAction ]))

更新

由于您希望游戏在您触摸任何地方时结束,因此请更改代码,使块设置一个变量来指示动画已执行并实现 touchesBegan 检查该变量,例如

let addAction = SKAction.runBlock({ self.redLightAnimationRuns = true })

[...]

// In touchesBegan
if touched
{
    if redLightAnimationRuns
    {
        endGame()
    }
}

使用 touchesBegan() 函数在屏幕上出现红灯时调用 GameOver() 函数(您可以通过变量控制)。

因此,当屏幕上出现红灯时,变量 redLightCurrent 设置为 true。在 TouchesBegan() 中,当 redLightCurrent 为真时,调用 gameOver() 函数,您可以在其中包含游戏结束时要执行的操作。这只会在屏幕上开始触摸时发生。

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

  super.touchesBegan(touches, withEvent: event)
  let array = Array(touches)
  let touch = array[0] as UITouch
  let touchLocation = touch.locationInNode(self)

  if redLightCurrent {
       gameOver()
     }
  }

此代码适用于新的 xCode 7 和 Swift 2.0