改变SKShapeNode的半径

6
我们如何在不重新创建SKShapeNode的情况下更改其半径?在头文件中,只有一个使用circleOfRadius语法的初始化器。

2
除了使用比例属性之外,没有其他选择。 - CodeSmile
2个回答

7
如果您使用路径创建SKShapeNode,可以在任何时候更改路径。请尝试以下操作:
class GameScene: SKScene {
    override func mouseDown(theEvent: NSEvent) {
        let location = theEvent.locationInNode(self)
        let node = self.nodeAtPoint(location)
        if let circle = node as? SizeableCircle { // clicking on an existing circle
            circle.radius = Double(arc4random_uniform(100))
        } else { // clicking on empty space
            self.addChild(SizeableCircle(radius: 100.0, position: location))
        }
    }
}

class SizeableCircle: SKShapeNode {

    var radius: Double {
        didSet {
            self.path = SizeableCircle.path(self.radius)
        }
    }

    init(radius: Double, position: CGPoint) {
        self.radius = radius

        super.init()

        self.path = SizeableCircle.path(self.radius)
        self.position = position
    }

    class func path(radius: Double) -> CGMutablePathRef {
        var path: CGMutablePathRef = CGPathCreateMutable()
        CGPathAddArc(path, nil, 0.0, 0.0, radius, 0.0, 2.0 * M_PI, true)
        return path
    }

}

与缩放不同的是,除非你对它们进行更改,否则设置的任何其他内容(例如线宽、文本子节点等)都不会改变。

谢谢,这非常有帮助! - LNI

2

Swift 4:

基本上,你可以使用特定的 TimeInterval 作为持续时间启动 scaleToscaleBySKAction,无论如何,我已将 Grimxn 类翻译到最新的 Swift 版本,以防你因其他原因而需要使用它:

class SizeableCircle: SKShapeNode {

    var radius: Double {
        didSet {
            self.path = SizeableCircle.path(radius: self.radius)
        }
    }

    init(radius: Double, position: CGPoint) {
        self.radius = radius

        super.init()

        self.path = SizeableCircle.path(radius: self.radius)
        self.position = position
    }

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

    class func path(radius: Double) -> CGMutablePath {
        let path: CGMutablePath = CGMutablePath()
        path.addArc(center: CGPoint.zero, radius: CGFloat(radius), startAngle: 0.0, endAngle: CGFloat(2.0*Double.pi), clockwise: false)
        return path
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接