如何在Swift中删除SKShapeNode

时间:2015-03-13 23:55:22

标签: xcode swift sprite-kit

我正在制作一个SpriteKit项目,其中一个游戏画面需要允许用户在屏幕上绘图。我希望有一个"删除所有"按钮和"撤消"按钮。但是,我无法找到如何在线删除路径。以下是我如何画线:

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(),但它没有用。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

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

var shapeNodes : [SKShapeNode] = []

将每个lineNode添加到shapeNodes

中的touchesBegan
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()
 }

答案 1 :(得分:0)

但是lineNode.removeFromParent()确实有用 - 或许你实际上没有调用它?在这里,我使用touchesEnded(touches:withEvent:)方法进行此操作,但您可以在任何您喜欢的地方拨打电话:

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