【问题标题】:Cannot assign value of type '[SKNode]' to type 'SKSpriteNode!'无法将类型“[SKNode]”的值分配给类型“SKSpriteNode!”
【发布时间】:2017-06-11 01:54:35
【问题描述】:

我正在使用 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)一行得到错误

【问题讨论】:

  • 你需要在那个 SKNode 上对 SKSpriteNode 类进行类型转换,我只知道如何用 Obj-C 来做,我不知道 swift (还) 抱歉
  • 你能解释一下 typecast 是什么意思吗?

标签: swift3 sprite-kit xcode8 ios10


【解决方案1】:

函数self.nodes(at: location) 返回一个包含与location 相交的所有SKNode 的数组。发生错误是因为您试图将整个 SKNodes 数组(即[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()
}

希望这会有所帮助!

【讨论】:

  • 好的,迭代数组的最佳方法是什么?
  • 好的,它修复了这个错误,但现在我在 fireButton sprite 的初始化时收到一个错误,显示 Thread 1 EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode=0x0)。我会尝试自己解决这个问题,因为我认为我已经问过一个关于这个错误的问题。如果您想帮忙,请随意,但我可能暂时不会回复。感谢您的帮助!
  • 不客气!第二个错误意味着您正在访问一个不存在的对象(它还没有被初始化,或者它已经被释放)。我认为问题可能出在您使用 ! .在强制解包之前尝试检查对象是否不为零。
  • 好的。感谢大家的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-30
  • 2019-12-03
  • 2017-08-07
  • 2021-03-08
  • 2016-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多