user2255273
user2255273

Reputation: 958

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?

Upvotes: 4

Views: 1465

Answers (2)

67cherries
67cherries

Reputation: 6951

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];
        }
    } 
}

Upvotes: 5

user2255273
user2255273

Reputation: 958

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

Upvotes: 3

Related Questions