Sprite Kit detects touch position

I want to start different actions depending on whether you touch the left or right half of the screen. So, the action is when you touch the left half, and the other when the right half is touched.

I suppose I can make a transparent button image that covers half the screen and use this code to trigger an action when touched, but I don't think that way. Is there a better way to determine the position of the touch?

+4
source share
2 answers

Override the touchesEnded:withEventor method touchesBegan:withEvent:to do this:

- (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];
        }
    } 
}
+5
source

, .

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

Source: https://habr.com/ru/post/1526615/


All Articles