检测SKSpriteNode是否离开屏幕底部并调用函数

时间:2015-08-02 14:15:59

标签: swift sprite-kit skspritenode skaction

如果 SKSpriteNode 离开 屏幕,我试图找到检测的方法< / strong>(我想称之为Game Over功能)。

我已经在一个函数中声明了节点(如果我做对了那么它不是全局的?)并且制作了SKAction并将节点移出屏幕然后将其删除。

这就是我提出的:

 var node = SKSpriteNode()

 let nodeTexture = SKTexture(imageNamed: "node")
 nodeTexture.filteringMode = .Nearest
 node = SKSpriteNode(texture: nodeTexture)

 let nodeFalling = SKAction.moveToY(-70, duration: 1.6)
 let nodeRemoving = SKAction.removeFromParent()
 node.runAction(SKAction.sequence([nodeFalling, nodeRemoving]))

 self.addChild(node)

现在我需要的是在节点离开屏幕时调用GameOver()。

我非常感谢每一个答案!

1 个答案:

答案 0 :(得分:3)

在您的场景中,您必须记住要检查的节点的引用,然后在update方法中执行以下操作:

    if node.position.y < -node.size.height/2.0 {
            node.removeFromParent()
            gameOver()

    }

编辑:

class MyScene: SKScene {
// ....

//here is the list of nodes which you want to check
var nodesToCheck = [SKSpriteNode]()

//here is your spawn function

func spawnNewNode() {
    var node = SKSpriteNode()

    let nodeTexture = SKTexture(imageNamed: "node")
    nodeTexture.filteringMode = .Nearest
    node = SKSpriteNode(texture: nodeTexture)

    let nodeFalling = SKAction.moveToY(-70, duration: 1.6)
    let nodeRemoving = SKAction.removeFromParent()
    node.runAction(SKAction.sequence([nodeFalling, nodeRemoving]))

    self.addChild(node)
    nodesToCheck.append(node)
}

//and here is the update method

override func update(currentTime: NSTimeInterval) {
    super.update(currentTime)

    // ... every other update logic

    for node in nodesToCheck {
        if node.position.y < -node.size.height/2.0 {
            node.removeFromParent()
            gameOver()
        }
    }
}

func gameOver() {
    println("Damn!")
}

}

当它们不再是场景成员时,别忘了从nodeToCheck数组中删除你的节点。