user8579808
user8579808

Reputation:

How to check which SCNNode is tapped in scenekit iOS

Currently i have three SCNNode in SceneView.i want to get indexpath like which cube is Tapped.

Here is my code of Tap Event

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


SCNNode *hitNode = hitTestResult.node;
}

Here is my code to create SCNNodes.

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];

I want like if i am tapping first cube than i should get indexpath Zero.how to achieve this ?

Upvotes: 1

Views: 341

Answers (1)

halileohalilei
halileohalilei

Reputation: 2280

I assume ArrBoxNode is the array in which you store your cubes. In that case, you can just check which of the nodes was hit with a simple for loop.

- (NSIndexPath*) indexPathFor:(SCNNode*) hitNode {
  for (int i = 0; i < [ArrBoxNode count]; i++) {
    SCNNode* node = ArrBoxNode[i];
    if (node == hitNode) {
      return [NSIndexPath indexPathForItem:i inSection:0];
    }
  }
  return nil;
}

Upvotes: 1

Related Questions