Search code examples
iphoneobjective-ctouchesbegan

Multiple touch on the iPhone issue


How can I make it so that while the user is playing on the joystick to move the character at the centre they can also touch the bottom right of the screen (the second touch) to fire the gun? I have looked at other questions but I still cant figure it out...

this is basically the code....:

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
//make the touch point...
UITouch *touch = [[event allTouches]anyObject];  
CGPoint point = [touch locationInView:touch.view];

if (//touching a certain area (on the joystick)) {
//do stuff
}

else if (point.x > 300 && point.y > 200) {
/fire method

}




}

so basically how do I call touchesBegan again to find the position of CGPoint point, and work out if the fire method should be called?

Thanks

EDIT:

I have tried to do that 2nd option and done this: in view controller.h I added:

@interface fireView: UIView 
@end 

and in .m I added:

@implementation fireView -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {         
NSLog(@"hi");
} 

@end 

....but it doesn't log/print "hi"?


Solution

  • Use 2 UIGestureRecognizers. You can create 2 invisible views of needed size - one for joystick and one for fire button. For every view use single gesture recognizer. And then you will be able to handle taps on these view by in different methods without checking if it was fire or joystick.

    Let's think you have 2 views - joystickView and fireView already. Then do it like

      UITapGestureRecognizer* fireTapGestureRec= [[UITapGestureRecognizer alloc] 
                                 initWithTarget:self action:@selector(fireTapped:)];
        fireTapGestureRec.delegate = self;
        fireTapGestureRec.numberOfTapsRequired = 1;
        fireTapGestureRec.numberOfTouchesRequired = 1;
        [fireView addGestureRecognizer:fireTapGestureRec];
        [fireTapGestureRec release];
    

    and write fireTapped: to handle the event. And the same thing for joystick.

    EDIT Second option (suggested in comments) Make subclasses of UIView, like

    @interface fireView: UIView
    @interface joystickView: UIView
    

    and for each subclass write it own touchesBegan: or touchesEnded: