Jun
04
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:

[c]
/**Touch event delegate
 * return YES if the event was handled
 * return NO if the event was not handled
 */
@protocol TouchEventsDelegate <NSObject>
@optional
- (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;
@end
[/c]

2) Associate the event handler with the director.

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

Example

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

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

And in ExampleAppDelegate.m, then I call

[c]
	[[Director sharedDirector] addEventHandler:self];
[/c]

like so:

[c]
- (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];
}
[/c]

And implement ccTouchesBegan:

[c]
-(BOOL)ccTouchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
	// Do something here
	return YES;
}

[/c]

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

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

2 Responses to “Cocos2d: Adding Handler To Touch Events”

  1. [...] Touch Event Handler: http://lethain.com/entry/2008/oct/20/touch-detection-in-cocos2d-iphone/ http://permadi.com/blog/2009/06/cocos2d-adding-handler-to-touch-events/ [...]

  2. [...] http://permadi.com/blog/2009/06/cocos2d-adding-handler-to-touch-events/ [...]