无法使用图像名称子类化 SKSpriteNode
Am unable to subclass SKSpriteNode using an image name
当我需要使用 .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)
我想将它移动到子class,但无论我尝试什么组合,总是会出现错误,例如:
Cannot convert value of type 'SKTexture' to expected argument type
'String'
或
Must call a designated initializer of the superclass 'SKSpriteNode'
如果我想使用 SKTexture,我可以子class SKSpriteNode。然而此时我想要 subclass 的 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")
}
}
当我需要使用 .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)
我想将它移动到子class,但无论我尝试什么组合,总是会出现错误,例如:
Cannot convert value of type 'SKTexture' to expected argument type 'String'
或
Must call a designated initializer of the superclass 'SKSpriteNode'
如果我想使用 SKTexture,我可以子class SKSpriteNode。然而此时我想要 subclass 的 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")
}
}