Reputation: 918
I'm making a SpriteKit project where one game screen needs to allow the user to draw on the screen. I want to have a "delete all" button and an "undo" button. However, I can't find out how to delete a path anywhere online. Here's how I'm drawing my lines:
var pathToDraw:CGMutablePathRef!
var lineNode:SKShapeNode!
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let touch = touches.anyObject() as UITouch
let touchLocation = touch.locationInNode(self)
pathToDraw = CGPathCreateMutable()
CGPathMoveToPoint(pathToDraw, nil, touchLocation.x, touchLocation.y)
lineNode = SKShapeNode()
lineNode.path = pathToDraw
lineNode.strokeColor = drawColor
self.addChild(lineNode)
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
let touch = touches.anyObject() as UITouch
let touchLocation = touch.locationInNode(self)
CGPathAddLineToPoint(pathToDraw, nil, touchLocation.x, touchLocation.y)
lineNode.path = pathToDraw
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {}
But now the problem is how can I delete them? I have tried lineNode.removeFromParent()
but it doesn't work. Any ideas?
Upvotes: 0
Views: 1399
Reputation: 24572
You can keep track of the SKShapeNodes
you draw on the screen in an array. First create a property shapeNodes
var shapeNodes : [SKShapeNode] = []
Add each lineNode
to the shapeNodes
in touchesBegan
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
//Your code
shapeNodes.append(lineNode)
}
On pressing delete all button you loop through the shapeNodes array and remove them one by one.
func deleteAllShapeNodes() {
for node in shapeNodes
{
node.removeFromParent()
}
shapeNodes.removeAll(keepCapacity: false)
}
For undo, you just have to delete the last node in the shapeNodes
array.
func undo() {
shapeNodes.last?.removeFromParent()
shapeNodes.removeLast()
}
Upvotes: 1
Reputation: 8333
But lineNode.removeFromParent()
does work--perhaps you're not actually calling it? Here, I'm doing it in your touchesEnded(touches:withEvent:)
method, but you can call this from anywhere you'd like:
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
lineNode.removeFromParent()
lineNode = SKShapeNode()
}
Upvotes: 0