4

I want to simply draw a line using SKShapeNode. I am using SpriteKit and Swift.

Here is my code so far:

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)

    }
}

Whenever i run it and try to draw a line the app crashes with the error: reason: 'Attemped to add a SKNode which already has a parent: SKShapeNode name:'(null)' accumulatedFrame:{{0, 0}, {0, 0}}'

Why is this happening?

CodeSmile
  • 64,284
  • 20
  • 132
  • 217
PoisonedApps
  • 716
  • 8
  • 21

1 Answers1

5

Well you are adding the same child instance over and over again. Create line node every time and add it everytime to the parent node, then it will solve your problem.

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)
    }
}
Sandeep
  • 20,908
  • 7
  • 66
  • 106
  • The app has stopped crashing but its not drawing a line. All i want to do is draw a line wherever the user moves his finger – PoisonedApps Dec 15 '14 at 21:49
  • Ok, as I mentioned in comment in your question, you are moving to the line and then drawing line to the same point, so, keep track when the touch begins and then keep on creating the line everytime the touch is moved. See my edits. – Sandeep Dec 15 '14 at 21:50
  • Thank you! i understand what you mean now. Really appreciated! – PoisonedApps Dec 15 '14 at 21:59
  • How i change it so that it draws one line rather than adding multiple lines. – PoisonedApps Dec 15 '14 at 22:39
  • Keep a reference to the path used and just add the lines to that path. Use the path for your shape node –  Dec 16 '14 at 18:27