Problem with cocos2D for iPhone and touch detection

后端 未结 7 1093
后悔当初
后悔当初 2021-02-01 09:03

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 o

7条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-01 09:40

    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!

提交回复
热议问题