无法指定类型'[SKNode]'的值来键入'SKSpriteNode!'

时间:2017-06-11 01:54:35

标签: swift3 sprite-kit xcode8 ios10

我正在使用SpriteKit在Swift 3中编写一个Galaga风格的游戏,我不断收到错误消息

  

无法指定'[SKNode]'类型的值来输入'SKSpriteNode!'

任何人都可以解释这意味着什么,以便我可以在将来自行修复它并给我一个可能的解决方案?

这是我收到错误的函数:

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

    for touch in touches {
        let location = (touch as UITouch).location(in: self)
        if fireButton = self.nodes(at: location) {
            shoot()
        } else {
            let touchLocation = touch.location(in: self)
            spaceship.position.x = touchLocation.x
        }
    }
}

我在if fireButton = self.nodes(at: location)

的行上收到错误

1 个答案:

答案 0 :(得分:0)

函数self.nodes(at: location)返回与location相交的所有SKNode的数组。发生此错误的原因是您尝试将整个SKNode数组(即[SKNode])分配给仅引用单个节点的变量。

另请注意,由于self.nodes(at: location)返回所有与特定位置相交的节点,因此您需要遍历节点数组以查找您要查找的节点。

要遍历数组,我建议更换行

if fireButton = self.nodes(at: location) {
        shoot()
}

let nodes = self.nodes(at: location)
for node in nodes {
    if node.name == "fireButton" {
        shoot()
    }
}

在您声明fireButton的地方为其指定名称,如

fireButton.name = "fireButton" 
// just an exmaple, rather store these names as constants somewhere in your code

这是最简单的方法,但你需要记住你给精灵的所有名字。一个替代方法是创建一个FireButton类作为SKSpriteNode的子类,将fireButton声明为FireButton的实例,而不是检查名称,你可以这样做

if node is FireButton { 
    shoot()
}

希望这有帮助!

相关问题