【问题标题】:how to have image in a class which inherits SKSpritenode如何在继承 SKSpritenode 的类中拥有图像
【发布时间】:2018-05-19 02:13:23
【问题描述】:

我可以像这样创建一个 SKSpriteNode 类的实例

let dog = SKSpriteNode(imageNamed: "Dog01")

但是,如果我想创建一个继承自 SKSpriteNode 的自定义类,我该怎么做呢?

例如

class Dog : SKSpriteNode {



}

看起来很简单,但我不知道怎么做。

【问题讨论】:

    标签: ios class sprite-kit swift4 skspritenode


    【解决方案1】:

    我找到了一种方法来做到这一点:

    init() {
    
        let texture = SKTexture(imageNamed: "Dog")
    
        super.init(texture: texture, color: UIColor.clear, size: texture.size())
    
    }
    

    我不知道为什么上述方法有效,但有些这样的方法无效:

    super.init(imageName: "Dog")
    

    我在哪里可以从 Apple 文档(任何其他来源)中了解允许和不允许的内容?谢谢。

    【讨论】:

    • SKSpriteNode(imageName: String) 不是一个合适的初始化器。是SKSpriteNode(imageNamed: String)
    • 那是我的打字错误。它应该是 super.init(imageNamed: "Dog") 。当然 Xcode 会指出这是一个错误。它仍然不起作用。
    • @MatthewtheCoder,您可以查看this github repo of a cool Spritekit Game。这个项目可能会消除你的困惑。查看 Player.swift 文件并使用您的项目来实现 SKSpriteNode 子类
    • @MatthewtheCoder,您有一个问题“我不知道为什么上述方法有效,但有些类似的方法无效:super.init(imageName: "Dog")”?答案是 SKSpriteNode 类只有一个指定的初始化器。如果你想继承 SKSpriteNode 类,你必须 super.init() 指定 SKSpriteNode 的特定初始化器。你应该在这里查看这个 Ray Wenderlich 教程:part 1part 2
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 2020-03-08
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    • 2021-05-20
    相关资源
    最近更新 更多