jonpeter
jonpeter

Reputation: 599

How to remove last placed child node?

I have touchesBegan discover and then place a node when a user taps the screen.

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)

However, I'm confused as to removing the last placed node in the view.

I attempted a simple

planeNode.removeFromParentNode()

but that did not achieve the results I was hoping for. Therefore, how would I achieve the desired result? I'm aware that removing the parent node is arbitrary, but i'm unsure how to call the last child node placed.

Upvotes: 1

Views: 1034

Answers (1)

nagam11
nagam11

Reputation: 133

You should create a reference to the last added node in your class.

var lastNode: SCNNode?

Then, let's say for example you want to remove the last node everytime you add a new one. In this case, you would create and add a new one, remove the lastNode and assign your newly created node as the last added node. So in your case, in the method addDot:

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

Upvotes: 2

Related Questions