更改SKShapeNode的半径

时间:2014-06-20 15:39:24

标签: ios sprite-kit swift

如何更改SKShapeNode的半径而不重新创建它?在头文件中,只有一个带有circleOfRadius语法的初始化器。

2 个答案:

答案 0 :(得分:6)

如果使用路径创建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
    }

}

此缩放与缩放之间的区别在于,您设置的任何其他内容(例如行宽,文本子节点等)都将更改,除非您制作它们。

答案 1 :(得分:1)

斯威夫特4:

基本上,您可以针对SKActionscaleTo启用scaleBy作为持续时间的特定TimeInterval,无论如何我将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
    }

}