xcode - Swift SpriteKit 中的子类化

标签 xcode swift subclassing exc-bad-instruction

我正在制作一款角色扮演游戏,您可以在其中选择用户的攻击方式。我正在尝试创建一个名为“Projectile”的父类(super class),其中描述了通用变量,以及更改变量的子类。但每当我覆盖变量的值时,我都会收到 EXC_BAD_INSTRUCTION。

import Foundation
import SpriteKit

class Projectile: SKNode {


    var texture: SKTexture!
    var projectileBody = SKSpriteNode()
    var projectile: SKEmitterNode!
    var negativeEffect: DefaultNegativeEffect!


    func setUpValues() {

        texture = SKTexture(imageNamed: "bokeh.png")
        projectileBody = SKSpriteNode()
        projectile = SKEmitterNode(fileNamed: "testbokeh.sks")
        negativeEffect = DefaultNegativeEffect(runningSpeed: 0)


    }

     override init() {
        super.init()
        projectileBody.texture = texture
        projectileBody.size = texture.size()
        projectileBody.position = self.position
        self.physicsBody = SKPhysicsBody(circleOfRadius: 2)
        self.physicsBody?.dynamic = true
        self.physicsBody?.categoryBitMask = PhysicsCategory.Projectile
        self.physicsBody?.contactTestBitMask = PhysicsCategory.Monster
        self.physicsBody?.collisionBitMask = PhysicsCategory.None
        self.physicsBody?.usesPreciseCollisionDetection = true
        projectile.position = self.position
        self.addChild(projectileBody)
        self.addChild(projectile)

    }


    func update() {

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

}
import Foundation
import SpriteKit

class FireBall: Projectile {

    override func setUpValues() {

        texture = SKTexture(imageNamed: "spark5.png")
        projectileBody = SKSpriteNode()
        projectile = SKEmitterNode(fileNamed: "testbokeh.sks")
        negativeEffect = DefaultNegativeEffect(runningSpeed: 0)

    }

}

最佳答案

看起来Projectile类在设置自己的属性之前调用了super.init(),并且根本不调用setUpValues(),这意味着你的变量属性永远不会有值。

Fireball 子类中,setUpValues 函数仍然没有被调用,并且您没有单独的 init() 函数,因此这是同样的问题:值永远不会被调用设置。

Swift 中的初始化规则与 Obj-C 略有不同,因为您需要在调用 super.init() 之前初始化所有存储的实例属性,并且还必须考虑如何处理继承的属性以确保您拥有一个完全/正确初始化的对象。

来自苹果的Swift Programming Guide:

  1. 指定的初始值设定项必须确保其类引入的所有属性在委托(delegate)给父类(super class)初始值设定项之前都已初始化。

  2. 在将值分配给继承的属性之前,指定的初始值设定项必须委托(delegate)给父类(super class)初始值设定项。如果没有,指定的初始化器分配的新值将被父类(super class)覆盖,作为其自身初始化的一部分。

关于xcode - Swift SpriteKit 中的子类化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27713243/

相关文章:

ios - 将选定的行复制到一个数组,该数组填充 Xcode 中的另一个 UITableView

ios - 试图理解类型属性,例如 static 和 swift 的 class 关键字

java 引用 Class<> 作为其子类型

ios - 将自己的功能添加到 iOS 库中

ios - 如何在 Xcode 6.2 beta 4 中创建 Apple Watch 目标

iphone - Xcode "Use of undeclared identifier"错误,编译/运行正常

iOS:如何解决以下警告问题?

objective-c - 如何在 Swift 中调用也有多个参数的 Objective C 方法

ios - 附加到文本文件不起作用

tensorflow - 是否有 L-BFGS 的 tf.keras.optimizers 实现?