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?
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)
}
}