2015-10-14 62 views
2

我試圖使用SceneKit檢測給定區域內的觸摸。使用一個幾何體完成此操作相當簡單(只需對場景視圖執行命中測試),但是,我有一個由SCNNode s(SCNVector3 s)數組定義的自定義區域。SceneKit在給定區域檢測觸摸

創建我的自定義區域,像這樣:

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 
{ 
    if (!self.isMakingLine) { 
     [super touchesBegan:touches withEvent:event]; 
    } else { 
     self.vectors = [[NSMutableArray alloc] init]; 
     NSArray <SCNHitTestResult *> *res = [self.sceneView hitTest:[[touches anyObject] locationInView:self.sceneView] options:@{SCNHitTestFirstFoundOnlyKey : @YES}]; 
     if (res.count) { 
      SCNHitTestResult *result = res.lastObject; 
      if (result.node == self.sphereNode) { 
       SCNNode *n = [SCNNode nodeWithGeometry:[SCNBox boxWithWidth:0.01 height:0.01 length:0.01 chamferRadius:0]]; 
       n.geometry.firstMaterial.diffuse.contents = [UIColor greenColor]; 
       n.position = result.localCoordinates; 
       [self.sphereNode addChildNode:n]; 
       [self.vectors addObject:n]; 
      } 
     } 
    } 
} 

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 
{ 
    if (!self.isMakingLine) { 
     [super touchesMoved:touches withEvent:event]; 
    } else { 
     NSArray <SCNHitTestResult *> *res = [self.sceneView hitTest:[[touches anyObject] locationInView:self.sceneView] options:@{SCNHitTestFirstFoundOnlyKey : @YES}]; 
     if (res.count) { 
      SCNHitTestResult *result = res.lastObject; 
      if (result.node == self.sphereNode) { 
       SCNNode *n = [SCNNode nodeWithGeometry:[SCNBox boxWithWidth:0.01 height:0.01 length:0.01 chamferRadius:0]]; 
       n.geometry.firstMaterial.diffuse.contents = [UIColor greenColor]; 
       n.position = result.localCoordinates; 
       [self.sphereNode addChildNode:n]; 
       [self.vectors addObject:n]; 
      } 
     } 
    } 
} 

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 
{ 
    if (!self.isMakingLine) { 
     [super touchesEnded:touches withEvent:event]; 
    } else { 
     NSArray <SCNHitTestResult *> *res = [self.sceneView hitTest:[[touches anyObject] locationInView:self.sceneView] options:@{SCNHitTestFirstFoundOnlyKey : @YES}]; 
     if (res.count) { 
      SCNHitTestResult *result = res.lastObject; 
      if (result.node == self.sphereNode) { 
       SCNNode *n = [SCNNode nodeWithGeometry:[SCNBox boxWithWidth:0.01 height:0.01 length:0.01 chamferRadius:0]]; 
       n.geometry.firstMaterial.diffuse.contents = [UIColor greenColor]; 
       n.position = result.localCoordinates; 
       [self.sphereNode addChildNode:n]; 
       [self.vectors addObject:n]; 
       self.isMakingLine = NO; 
      } 
     } 
    } 
} 

所以給我的陣列的SCNBox ES我怎樣才能檢測是否有其他點落在他們的中間?

回答

4

SCNView符合SCNSceneRenderer協議,這提供了一種方法projectPoint:(SCNVector3)point,它會在3D場景中取一個點並將其投影到2D視圖座標。

我試着將你的盒子節點的位置投影到2D視圖座標中,然後檢查你的2D觸摸座標是否在這個2D形狀內。 There's another SO question這將有助於此。

+0

謝謝,這是一個非常好的提示。 –