触摸屏幕时,如何完成游戏?

时间:2015-01-11 09:06:53

标签: ios animation swift touch sprite-kit

我希望屏幕上的游戏和在特定动画期间触摸屏幕时停止游戏。

    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语句,如果是,那么具体是什么?

提前谢谢你!

2 个答案:

答案 0 :(得分:0)

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

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()
    }
}

答案 1 :(得分:0)

使用touchesBegan()函数在屏幕上显示红灯时调用GameOver()函数(可以使用变量控制)。

因此,当红灯亮起时,变量redLightCurrent设置为true。在TouchesBegan()中,当redLightCurrent为true时,然后调用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

相关问题