swift - 无法使用图像名称对 SKSpriteNode 进行子类化

标签 swift sprite-kit

当我需要使用 .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/

相关文章:

swift - 如何在 Swift 中获取 NSImage 对象的 png 表示

swift - 如何在 Swift 中创建 QuickBlox session

xcode - 无法更改 NSSplitView 上的委托(delegate)

Swift 不能在结构内部使用任何变量

ios - 在 skview 中创建按钮以指向不同的场景

Swift Sprite 套件游戏 : detect touch and execute separate code for different parts of screen?

swift - SKSpriteNode 隐藏在父节点下方

Swift 如果您在设置中指定非零格式字典,则您的委托(delegate)必须响应选择器 captureOutput :didFinishProcessingPhoto

ios - 使用 SpriteKit 传递多个数组 - UIColor 和 String

ios - Swift 错误 : "Cannot find interface declaration for ' SKScene', 的父类(super class)”