如何只允许在场景中的特定区域触摸?

时间:2015-08-14 18:05:01

标签: ios objective-c sprite-kit skscene

我想将触摸设置为仅在屏幕的一部分中,我试图在屏幕的一部分中添加节点层,不允许触摸并禁用用户交互

_mainLayer.userInteractionEnabled = NO;

但它没有任何想法如何做到这一点?

2 个答案:

答案 0 :(得分:1)

以下是如何将触摸事件限制在特定区域的示例:

<强>夫特

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    for touch in (touches as! Set<UITouch>) {
        let location = touch.locationInNode(self)

        switch (location) {
        case let point where CGRectContainsPoint(rect, point):
            // Touch is inside of a rect
            ...
        case let point where CGPathContainsPoint(path, nil, point, false):
            // Touch is inside of an arbitrary shape
            ...
        default:
            // Ignore all other touches
            break
        }
    }
}

<强>的OBJ-C

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    for (UITouch *touch in touches) {
        CGPoint location = [touch locationInNode:self];

        if (CGRectContainsPoint(rect, location)) {

        }
        else if (CGPathContainsPoint(path, nil, location, false)) {

        }
    }
}

答案 1 :(得分:0)

我没有足够的评论空间来进一步深入,所以这只是一个准答案。

在评论的屏幕截图中,您似乎不希望在视图最底部200像素高的区域中的任何位置识别触摸。

您可以让视图采用UIGestureRecognizerDelegate协议并实现shouldReceiveTouch方法。尝试像这样实现该方法(我实际上有一段时间没有使用Objective-C,所以如果任何语法完全没有,请原谅我):

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch 
{
    CGPoint touchPointInView = [touch locationInView:self];

    if (touchPointInView.y >= CGRectGetMaxY(self.bounds) - 200)
    {
        return NO;
    }
    else
    {
        return YES;
    }
}

不要忘记设置手势识别器的委托(在视图的构造函数中往往是一个好地方):

gestureRecognizer.delegate = self;