Detecting Touches in Cocos2D

Detect Touch

Detect Touch

This post will help you to enable touches detection & handling.

Step 1) Go to layer & open implementation file.

Step 2) set isTouchesEnabled to YES in your layer’s init method.


-(id) init
	if( (self=[super initWithColor:ccc4(255, 255, 255, 255)])) {
        self.isTouchEnabled=YES; // this line is important
        spritePlayer = [CCSprite spriteWithFile:@"Player.png"];
        [spritePlayer setPosition:ccp(spritePlayer.contentSize.width/2,WINSIZE.height/2)];
        [self addChild:spritePlayer];
        [self schedule:@selector(addTargetSprite) interval:1];
	return self;

Step 3) now place following methods to detect touch triggers.

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {


- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {


- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {


- (void)ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {


To detect the location & converting it to cocos format try to understand following code.

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    CGPoint touchPoint = [[touches anyObject] locationInView:[[CCDirector sharedDirector] openGLView]];
    touchPoint=[[CCDirector sharedDirector] convertToGL:touchPoint];
    NSLog(@"Cocos touch point is (%.2f,%.2f)",touchPoint.x,touchPoint.y);

Thanks & Regards,
Neon Spark.

Leave a Reply

Your email address will not be published. Required fields are marked *