【问题标题】:Make SKSpriteNode subclass using Swift使用 Swift 创建 SKSpriteNode 子类
【发布时间】:2014-10-13 09:28:55
【问题描述】:

我正在尝试创建作为 SKSpriteNode 子类的类,并且我想向它添加其他属性和函数。但在第一步中,我遇到了一个错误。 这是我的代码:

import SpriteKit

class Ball: SKSpriteNode {
    init() {
        super.init(imageNamed: "ball")
    }
}

这不是编译错误,而是运行时错误。它说:Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)fatal error: use of unimplemented initializer 'init(texture:)' for class Project.Ball

我该如何解决?

【问题讨论】:

  • 您能发布您遇到的错误吗?
  • 它说:Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)。还有fatal error: use of unimplemented initializer 'init(texture:)' for class Project.Ball

标签: ios swift sprite-kit subclass skspritenode


【解决方案1】:

您必须为SKSpriteNode 调用指定的初始化程序。我真的很惊讶您没有收到关于未完全实现 SKSpriteNode 的另一个错误,您可能使用的是较旧的 Xcode6 测试版吗?

由于必须使用指定的初始化器,所以需要调用super.init(texture: '', color: '', size: '')

应该是这样的:

class Ball: SKSpriteNode {
    init() {
        let texture = SKTexture(imageNamed: "ball")
        super.init(texture: texture, color: nil, size: texture.size())
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

注意: 我还为 Xcode 需要的 NSCoder 添加了 init

【讨论】:

  • SKSpriteNode 没有 init() 初始化程序,因此您不应该在声明中使用 override
  • 有人能帮我看看这个 Ball 类是如何在另一个 Swift 文件中初始化的吗?我无法让它运行:-/
  • 颜色在SKSpriteNode的指定初始化器上不能为空,所以调用super.init时需要使用UIColor.clearColor()
  • SKColor.clearColor() 可以替代 leolobato 所写的内容。它是 SpriteKit 库的一部分。
  • 最新的 Xcode (10.0) 不接受 nil 作为颜色。我不得不改用 .clear(基于 leolobato 和 JKT 的 cmets)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多