Subclassing SKShapeNode with Swift

北城余情 提交于 2019-12-06 18:24:30

问题


I'm trying to subclass SKShapeNode with Swift. So far I've got something like this:

import UIKit
import SpriteKit

class STGridNode: SKShapeNode {

    init() {
        super.init()
        self.name = "STGridNode"
        self.fillColor = UIColor(red: 0.11, green: 0.82, blue: 0.69, alpha: 1)
    }

}

In my code I want so do something along the lines of:

let s = STGridNode(rectOfSize: CGSize(width: 100, height: 100))

So my question is - how do I implement rectOfSize in the initialiser for STGridNode? I've tried:

init(rectOfSize: CGPoint) {
    super.init(rectOfSize: rectOfSize);
}

But that gives an error: 'Could not find an overload for init that accepts the supplied arguments'


回答1:


You have two problems with the code you tried:

  1. rectOfSize in SKShapeNode takes a CGSize not a CGPoint
  2. rectOfSize in SKShapeNode is a convenience initializer so you won't be able to call it from a subclass. You will have to call super.init() and implement the rect functionality yourself

You can do something like this:

init(rectOfSize: CGSize) {
    super.init()

    var rect = CGRect(origin: CGPointZero, size: rectOfSize)
    self.path = CGPathCreateWithRect(rect, nil)
}


来源:https://stackoverflow.com/questions/24235185/subclassing-skshapenode-with-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!