Swift SKShapeNode不接受初始化

时间:2017-12-29 22:22:27

标签: swift sprite-kit skshapenode

我无法获得SKShapeNode的子类来接受初始化。为了解决这个问题,我试图通过这里发布的示例Adding Convenience Initializers in Swift Subclass。我正在使用的代码如下。

class Ground1 : SKShapeNode {

override init() {
    super.init()
    print("Hello1")
}

convenience init(width: CGFloat, point: CGPoint) {
    var points = [CGPoint(x: -900, y: -300),
                  CGPoint(x: -600, y: -100),
                  CGPoint(x: -100, y: -300),
                  CGPoint(x: 2, y: 150),
                  CGPoint(x: 100, y: -300),
                  CGPoint(x: 600, y: -100),
                  CGPoint(x: 900, y: -300)]
    self.init(splinePoints: &points, count: points.count)
    lineWidth = 5
    strokeColor = UIColor.orange
    physicsBody = SKPhysicsBody(edgeChainFrom: path!)
    physicsBody?.restitution = 0.75
    physicsBody?.isDynamic = false
    print("Hello2")
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

}

初始化时,方便init()被忽略并且不被使用。导致没有形状添加到场景中。我做错了什么?

1 个答案:

答案 0 :(得分:0)

感谢0x141E,谁回合向我指出正确的方向。我发现这有效,但代码看起来很乱。在这里详细解释了以这种方式进行初始化的原因Adding Convenience Initializers in Swift Subclass。虽然我因为使用​​了splinePoints并分配给路径而被抛弃了寻找解决方案。

class Ground1 : SKShapeNode {

    override init() {
        super.init()
    }

    convenience init(name: String) {
        var points = [CGPoint(x: -900, y: -300),
                      CGPoint(x: -600, y: -100),
                      CGPoint(x: -100, y: -300),
                      CGPoint(x: 2, y: 150),
                      CGPoint(x: 100, y: -300),
                      CGPoint(x: 600, y: -100),
                      CGPoint(x: 900, y: -300)]
        self.init(splinePoints: &points, count: points.count)
        lineWidth = 5
        strokeColor = UIColor.orange
        physicsBody = SKPhysicsBody(edgeChainFrom: self.path!)
        physicsBody?.restitution = 0.75
        physicsBody?.isDynamic = false
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}