如何删除最后放置的子节点?

How to remove last placed child node?

我有 touchesBegan 在用户点击屏幕时发现并放置一个节点。

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    if let touchLocation = touches.first?.location(in: sceneView)
    {
        let hitTestResults = sceneView.hitTest(touchLocation, types: .featurePoint)

        if let hitResult = hitTestResults.first
        {
            addDot(at: hitResult)
        }
    }
}

func addDot(at hitResult : ARHitTestResult)
{

    let imagePlane = SCNPlane(width: 0.1, height: 0.1)
    imagePlane.firstMaterial?.diffuse.contents = UIImage(named: "helmet_R.png")
 let planeNode = SCNNode(geometry: imagePlane)

   planeNode.position = SCNVector3(hitResult.worldTransform.columns.3.x, hitResult.worldTransform.columns.3.y, hitResult.worldTransform.columns.3.z)

    planeNode.constraints = [SCNBillboardConstraint()]


    sceneView.scene.rootNode.addChildNode(planeNode)

但是,我对删除视图中最后放置的节点感到困惑。

我尝试了一个简单的

planeNode.removeFromParentNode()

但这并没有达到我希望的结果。因此,我将如何达到预期的结果?我知道删除父节点是任意的,但我不确定如何调用最后放置的子节点。

您应该在 class 中创建对最后添加的节点的引用。

var lastNode: SCNNode?

然后,假设您想在每次添加新节点时删除最后一个节点。在这种情况下,您将创建并添加一个新节点,删除 lastNode 并将新创建的节点分配为最后添加的节点。所以在你的情况下,在方法 addDot:

 sceneView.scene.rootNode.addChildNode(planeNode)
 lastNode?.removeFromParentNode()
 lastNode = planeNode