Problem with cocos2D for iPhone and touch detection

maw picture maw · Dec 18, 2008 · Viewed 19.6k times · Source

I just don't get it. I use cocos2d for development of a small game on the iPhone/Pod. The framework is just great, but I fail at touch detection. I read that you just need to overwrite the proper functions (e.g. "touchesBegan" ) in the implementation of a class which subclasses CocosNode. But it doesn't work. What could I do wrong?

the function:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{NSLog(@"tickle, hihi!");}

did I get it totally wrong?

Answer

Genericrich picture Genericrich · Dec 19, 2008

Layer is the only cocos2d class which gets touches.

The trick is that ALL instances of Layer get passed the touch events, one after the other, so your code has to handle this.

I did it like this:

-(BOOL)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView: [touch view]];
CGPoint cLoc = [[Director sharedDirector] convertCoordinate: location];

float labelX = self.position.x - HALF_WIDTH;
float labelY = self.position.y - HALF_WIDTH;
float labelXWidth = labelX + WIDTH;
float labelYHeight = labelY + WIDTH;

if( labelX < cLoc.x &&
    labelY < cLoc.y &&
    labelXWidth > cLoc.x &&
    labelYHeight > cLoc.y){
        NSLog(@"WE ARE TOUCHED AND I AM A %@", self.labelString);
        return kEventHandled;
    } else {
        return kEventIgnored;
    }

}

Note that the cocos2d library has a "ccTouchesEnded" implementation, rather than the Apple standard. It allows you to return a BOOL indicating whether or not you handled the event.

Good luck!