SKNode上的UITapGestureRecognizer:将坐标从UIView转换为SKNode

时间:2015-03-17 22:30:55

标签: ios objective-c sprite-kit uitapgesturerecognizer

我在UITapGestureRecognizer上有一个UIPanGestureRecognizer和一个UIView,上面有一个SKScene。平移手势识别器从左向右移动SKNode,并且我希望Tap手势识别器检测到平移的SKNode的孩子。平移工作正常,但我在检测水龙头时遇到问题 - Tap Gesture会触发相关方法,但我不确定如何将坐标从视图转换到场景到节点以检测水龙头是否在其中一个子节点。

UIView(带手势)→SKScene→平移节点→平移节点的孩子

如何检查点按手势的触摸坐标是否为任何给定的SKNode?

-(void)tapAction:(UITapGestureRecognizer*)sender{
if (sender.state == UIGestureRecognizerStateEnded)
{
    // handling code
    CGPoint touchLocation = [sender locationOfTouch:0 inView:sender.view];
    NSLog(@"TAP %@", NSStringFromCGPoint(touchLocation)
          );
    for (SKLabelNode *node in _containerNode.children) {

        if ([node containsPoint:[node convertPoint:touchLocation fromNode:self.parent]]) {
            //This is where I want the tap to be detected.
        }

        CGPoint checkPoint = [node convertPoint:touchLocation fromNode:self.scene];
        NSLog(@"CheckPoint %@", NSStringFromCGPoint(checkPoint)
              );
        //NSLog(@"iterating nodes");
        if ([node containsPoint:checkPoint]) {
            NSLog(@"touch match %@", node);

        }
    }
}

}

3 个答案:

答案 0 :(得分:8)

最后,我需要从建议的步骤中做更多的步骤 - 从SKView→SKScene转换到包含我正在测试的节点的SKNode。

    CGPoint touchLocation           = [sender locationOfTouch:0 inView:sender.view];
    CGPoint touchLocationInScene    = [[self.scene view] convertPoint:touchLocation toScene:self.scene];
    CGPoint touchLocationInNode     = [self.scene convertPoint:touchLocationInScene toNode:_containerNode];

答案 1 :(得分:6)

您应该使用convertPointFromView:

将视图坐标转换为场景坐标
CGPoint touchLocationInView = [sender locationOfTouch:0 inView:sender.view];
CGPoint touchLocationInScene = [self convertPointFromView:touchLocationInView];

然后,您可以检测使用哪个标签节点,

for (SKLabelNode *node in self.children) {

    if ([node containsPoint:touchLocationInScene]) {
        //This is where I want the tap to be detected.
    }

}

答案 2 :(得分:3)

之前我没有使用过SceneKit,但是从文档看起来你需要使用SKView方法convertPoint:toScene:将手势识别器的拍子坐标从视图坐标转换为场景坐标。然后,您需要测试场景中的节点以确定点击了哪个节点。