Cocos2d: Adding Handler To Touch Events
June 4, 2009

When using the Director on Cocos2d and you have a Scene object in the window, your program will not receive touch events. So, your UIApplicationDelegate implementation will not receive touchesBegan notification.

You can override this behavior by


1) implementing the TouchEventsDelegate protocol, which has the following specification:

/**Touch event delegate
 * return YES if the event was handled
 * return NO if the event was not handled
@protocol TouchEventsDelegate <NSObject>
- (BOOL)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (BOOL)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (BOOL)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (BOOL)ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;

2) Associate the event handler with the director.

[[Director sharedDirector] addEventHandler:(id<TouchEventsDelegate>)touchEventDelegateHandler];


For example, in my ExampleAppDelegate.h, I can do this

#import "cocos2d.h"
@interface ExampleAppDelegate : NSObject <UIApplicationDelegate, TouchEventsDelegate> {
 	UIWindow *window;
	Scene* mScene1;

And in ExampleAppDelegate.m, then I call

	[[Director sharedDirector] addEventHandler:self];

like so:

- (void)applicationDidFinishLaunching:(UIApplication *)application
	// Init the window
	window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

	// cocos2d will inherit these values
	[window setUserInteractionEnabled:YES];
	[window setMultipleTouchEnabled:NO];

	[[Director sharedDirector] attachInView:window];
	[[Director sharedDirector] addEventHandler:self];

	// Do other initialization

	mScene1=[Scene node];
	[[Director sharedDirector] runWithScene: mScene1];
	[window makeKeyAndVisible];


And implement ccTouchesBegan:

-(BOOL)ccTouchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
	// Do something here
	return YES;

If you need to handle the other touch events (ccTouchesMoved, ccTouchesEnded, etc) then implement them as well.

Alternatively, the event can be redirected to some other class that implements TouchEventsDelegate.
To dis-associate, an TouchEventsDelegate, use

[[Director sharedDirector] removeEventHandler:(id<TouchEventsDelegate>)touchEventDelegateHandler];