ios - 用 SKShapeNode 画一条线

标签 ios swift sprite-kit skshapenode

我想简单地使用 SKShapeNode 画一条线。我正在使用 SpriteKit 和 Swift。

到目前为止,这是我的代码:

var line = SKShapeNode()
var ref = CGPathCreateMutable()

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)

    }
}

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {

    for touch: AnyObject in touches {
        let locationInScene = touch.locationInNode(self)

        CGPathMoveToPoint(ref, nil, locationInScene.x, locationInScene.y)
        CGPathAddLineToPoint(ref, nil, locationInScene.x, locationInScene.y)
        line.path = ref
        line.lineWidth = 4
        line.fillColor = UIColor.redColor()
        line.strokeColor = UIColor.redColor()
        self.addChild(line)

    }
}

每当我运行它并尝试画一条线时,应用程序就会因错误而崩溃: 原因:'试图添加一个已经有父节点的 SKNode:SKShapeNode 名称:'(空)' accumulatedFrame:{{0, 0}, {0, 0}}'

为什么会这样?

最佳答案

好吧,您一遍又一遍地添加相同的子实例。每次创建行节点,每次添加到父节点,就解决了你的问题。

var ref = CGPathCreateMutable()

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    if let touch = touches.anyObject() as? UITouch {
        let location = touch.locationInNode(self)
        CGPathMoveToPoint(ref, nil, location.x, location.y)
    }
}

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {

    for touch: AnyObject in touches {
        let locationInScene = touch.locationInNode(self)
        var line = SKShapeNode()
        CGPathAddLineToPoint(ref, nil, locationInScene.x, locationInScene.y)
        line.path = ref
        line.lineWidth = 4
        line.fillColor = UIColor.redColor()
        line.strokeColor = UIColor.redColor()
        self.addChild(line)
    }
}

关于ios - 用 SKShapeNode 画一条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27493261/

相关文章:

ios - 在 Swift 中为一个 tabBarItem 设置 tintColor

swift - 如何在启动 OSX spritekit 应用程序时设置自定义光标?

Xcode:使用 Swift 将默认自定义字体添加到 SKLabelNode

ios - 在 iphone sdk 的屏幕中移动对象

ios - 修改 UIView 扩展的所有子项一次

ios - 发送到 destinationViewController 的无法识别的选择器

ios - 未检测到 SpriteKit 碰撞

ios - 无法使用自动布局将简单的自调整大小 Collection View 单元格调整为标签大小

json - 在 Swift 中为 JSON 动态组装复杂的多维字典

ios - 在 "let"常量变量中赋值,它在 cocoapods 中