如何在 Swift 中删除 SKShapeNode

How to delete SKShapeNode in Swift

我正在制作一个 SpriteKit 项目,其中一个游戏屏幕需要允许用户在屏幕上绘图。我想要一个 "delete all" 按钮和一个 "undo" 按钮。但是,我无法找到如何在线删除任何地方的路径。这是我画线的方式:

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

但现在的问题是如何删除它们?我已经尝试 lineNode.removeFromParent() 但它不起作用。有什么想法吗?

但是 lineNode.removeFromParent() 确实有效——也许您实际上并没有调用它?在这里,我在您的 touchesEnded(touches:withEvent:) 方法中执行此操作,但您可以从任何您喜欢的地方调用它:

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
    lineNode.removeFromParent()
    lineNode = SKShapeNode()
}

您可以跟踪 SKShapeNodes 您在屏幕上绘制的数组。首先创建一个属性shapeNodes

var shapeNodes : [SKShapeNode] = []

将每个 lineNode 添加到 touchesBegan

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

    //Your code
    shapeNodes.append(lineNode)
}

按下删除所有按钮后,您将遍历 shapeNodes 数组并将它们一一删除。

func deleteAllShapeNodes() {

    for node in shapeNodes
    {
        node.removeFromParent()
    }
    shapeNodes.removeAll(keepCapacity: false)
}

要撤消,只需删除 shapeNodes 数组中的最后一个节点。

 func undo() {
    shapeNodes.last?.removeFromParent()
    shapeNodes.removeLast()
 }