当我需要使用 .png 图像时,我在子类化 SKSpriteNode 时遇到了麻烦,并且我在 Google 上找到的所有帮助都只提到了 SKTexture。
在我的常规类(class)中,这段代码有效:
let circle = SKSpriteNode(imageNamed: "slot")
circle.setScale(1.0)
circle.anchorPoint = CGPoint(x: 0, y: 0.5)
circle.position = CGPoint(x: 1000, y: 500)
self.addChild(circle)
我想将其移至子类,但无论我尝试哪种组合,总是会遇到如下错误:
Cannot convert value of type 'SKTexture' to expected argument type 'String'
或
Must call a designated initializer of the superclass 'SKSpriteNode'
如果我想使用 SKTexture,我可以对 SKSpriteNode 进行子类化。然而此时此刻,我想要子类化的 init 是 SKSpriteNode(imageNamed: String)
这是我正在尝试做的事情,但我当然会遇到错误
class MyBall : SKSpriteNode{
init(iNamed: String){
super.init(imageNamed: iNamed)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
最佳答案
只需在 super 上使用完整的初始化程序,就像这样......
class MyBall : SKSpriteNode{
init(iNamed: String) {
let texture = SKTexture(imageNamed: iNamed)
super.init(texture: texture, color: .clear, size: texture.size())
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
关于swift - 无法使用图像名称对 SKSpriteNode 进行子类化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63065421/