Search code examples
iosobjective-cxcodescenekitscnnode

How to remove SCNNode when Tap on it?


I have Creat Cubes using SceneView and i want to disappear cube on which Tap action. How can achieve it?

Here is my code to create Cube

     SCNBox *Box = [SCNBox boxWithWidth:2.0 height:2.0 length:2.0 
     chamferRadius:Radius];


     Box.firstMaterial.diffuse.contents = [UIColor whiteColor];
     SCNNode *cubeNode = [SCNNode nodeWithGeometry:Box];
     [ArrBoxNode addObject:cubeNode];

     self.sceneView.backgroundColor = [UIColor redColor];
     self.view.backgroundColor  = [UIColor grayColor];

     cubeNode.position = SCNVector3Make(4,0,0);

     [scene.rootNode addChildNode:cubeNode];
     self.sceneView.scene = scene;
     [self.sceneView sizeToFit];




 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
  {
      UITouch *touch = [touches anyObject];
      CGPoint touchPoint = [touch locationInView:self.sceneView];
      SCNHitTestResult *hitTestResult = [[self.sceneView 
      hitTest:touchPoint options:nil] firstObject];
      SCNNode *hitNode = hitTestResult.node;

      for (SCNNode *node in ArrBoxNode) {
         [node removeFromParentNode];
   } 
 }

but I'm not able to remove Node from Tap action. Can you please help me, and give better suggestions, thank you... :)


Solution

  • You need remove the node you are touching using [hitNode removeFromParentNode];

    Code

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
      {
        UITouch *touch = [touches anyObject];
        CGPoint touchPoint = [touch locationInView:self.sceneView];
        SCNHitTestResult *hitTestResult = [[self.sceneView hitTest:touchPoint options:nil] firstObject];
        SCNNode *hitNode = hitTestResult.node;
        [hitNode removeFromParentNode];
    }