简体   繁体   English

Sprite Kit检测触摸位置

[英]Sprite Kit detect position of touch

I want to run different actions depending on if you touch the left or right half of the screen. 我想根据您是否触摸屏幕的左半部分或右半部分来执行不同的操作。 So an action when you touch the left half, and another when the right half is touched. 触摸左半部分时的动作,触摸右半部分时的动作。

I suppose I could make a transparent button image that covers half of the screen and use this code to run an action when touched, but I don't think that's the way to go. 我想我可以创建一个覆盖屏幕一半的透明按钮图像,并在触摸时使用此代码执行操作,但我不认为这是要走的路。 Is there a better way to detect the position of a touch? 有没有更好的方法来检测触摸的位置?

Override the touchesEnded:withEvent or touchesBegan:withEvent: method to do this: 覆盖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];
        }
    } 
}

I came up with the following code and it works perfect. 我提出了以下代码,它完美无缺。

-(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..
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM