Sprite Kit检测触摸位置

4

我希望能够根据触摸屏幕左半部分或右半部分运行不同的操作。因此,当您触摸左半部分时执行一项操作,而当您触摸右半部分时执行另一项操作。

我想我可以制作一个透明的按钮图像,覆盖屏幕的一半,并使用这个代码在触摸时运行一个操作,但我认为这不是正确的方法。有没有更好的方法来检测触摸的位置?


你可以使用手势识别器代替按钮。然后获取触摸事件的位置,并确定该点在屏幕上的位置。 https://dev59.com/tGQn5IYBdhLWcg3wt5Eg - Dan Watkins
谢谢你的帮助,但我认为我想出了一个相当不错的解决方案。(请看答案) - user2255273
2个回答

5

重写touchesEnded:withEventtouchesBegan:withEvent:方法来实现此操作:

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];

    if(touch){
        if([touch locationInView:self.view]>self.size.width/2){
            [self runTouchOnRightSideAction];
        }else{
            [self runTouchOnLeftSideAction];
        }
    } 
}

谢谢,但我刚刚找到了解决方案并在几分钟前发布了它。 - user2255273
@user2255273,抱歉啊,我正在回答问题的时候你发了你的回答。 - 67cherries
没问题,你的版本更干净!谢谢。 - user2255273

3
我想到了以下代码,它完美地运行了。
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInNode:self];

    // If left half of the screen is touched
    if (touchLocation.x < self.size.width / 2) {
        // Do whatever..
    }

    // If right half of the screen is touched
    if (touchLocation.x > self.size.width / 2) {
        // Do whatever..
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接