问题描述
我正在使用 SpriteKit 在 Swift 3 中编写 Galaga 风格的游戏,但我不断收到错误消息,提示
I'm writing a Galaga-style game in Swift 3 with SpriteKit and I keep getting an error that says
无法将[SKNode]"类型的值分配给SKSpriteNode!"类型
谁能解释一下这意味着什么,以便我将来可以自己修复它并给我一个可能的解决方案?
Can anyone explain what this means so that I can fix it myself in the future and also give me a possible solution?
这是我得到错误的函数:
Here's the function where I get the error:
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)
推荐答案
self.nodes(at: location)
函数返回与 location
相交的所有 SKNode 的数组.发生错误是因为您试图将整个 SKNode 数组(即 [SKNode]
)分配给仅引用单个节点的变量.
The function self.nodes(at: location)
returns an array of all SKNodes that intersect location
. The error occurs because you are trying to assign the whole array of SKNodes (i.e. [SKNode]
) to a variable that references only a single node.
另请注意,由于 self.nodes(at: location)
返回与特定位置相交的所有节点,因此您需要遍历节点数组以找到您要查找的节点.
Also note that since self.nodes(at: location)
returns all the nodes that intersect the specific location, you will need to iterate through the array of nodes to find the node you are looking for.
要遍历数组,我建议替换行
To iterate through the array, I would suggest to replace the lines
if fireButton = self.nodes(at: location) {
shoot()
}
与
let nodes = self.nodes(at: location)
for node in nodes {
if node.name == "fireButton" {
shoot()
}
}
并在声明 fireButton
的地方为其指定一个名称,如
And at the place where you declare fireButton
assign it a name as in
fireButton.name = "fireButton"
// just an exmaple, rather store these names as constants somewhere in your code
这是最简单的方法,但您需要记住为精灵取的所有名称.另一种方法是创建一个 FireButton
类作为 SKSpriteNode 的子类,将 fireButton
声明为 FireButton
的实例,而不是检查名称,而是可以做
That's the easiest way, but you need to remember all the names you gave to your sprites. An alterantive is to create a FireButton
class as a subclass of SKSpriteNode, declare fireButton
as an instance of FireButton
and instead of checking for names, you can do
if node is FireButton {
shoot()
}
希望这会有所帮助!
这篇关于无法将“[SKNode]"类型的值分配给“SKSpriteNode!"类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!