Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 647
user2255273 Avatar asked Feb 14 '23 19:02

user2255273


2 Answers

Override the touchesEnded:withEvent or touchesBegan:withEvent: method 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];
        }
    } 
}
like image 93
67cherries Avatar answered Feb 28 '23 16:02

67cherries


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..
    }
}
like image 27
user2255273 Avatar answered Feb 28 '23 15:02

user2255273