我正在使用cocos2d为iPhone开发一款2D游戏.
我在游戏中使用了很多小精灵(图像).我想触摸两个相似类型的精灵(图像),然后两个精灵(图像)将被隐藏.
如何检测特定精灵(图像)中的触摸?
更好的方法是实际使用精灵本身的边界框(这是一个CGRect).在这个示例代码中,我将所有精灵放在NSMutableArray中,并且我简单地检查精灵触摸是否在边界框中.确保在init中打开触摸检测.如果你注意到我也通过返回YES(如果我使用触摸)或否(如果我不这样做)接受/拒绝图层上的触摸
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event { CGPoint location = [self convertTouchToNodeSpace: touch]; for (CCSprite *station in _objectList) { if (CGRectContainsPoint(station.boundingBox, location)) { DLog(@"Found sprite"); return YES; } } return NO; }
按照乔纳斯的指示,再添加一点......
- (void)ccTouchesBegan:(NSSet*)touches withEvent:(UIEvent*)event { UITouch* touch = [touches anyObject]; CGPoint location = [[[Director sharedDirector] convertCoordinate: touch.location]; CGRect particularSpriteRect = CGMakeRect(particularSprite.position.x, particularSprite.position.y, particularSprite.contentSize.width, particularSprite.contentSize.height); if(CGRectContainsPoint(particularSpriteRect, location)) { // particularSprite touched return kEventHandled; } }
您可能需要调整x/ya以适应Cocos中的"居中定位"
在包含您的精灵的图层中,您需要说:
self.isTouchEnabled = YES;
然后你可以使用你在UIView中使用的相同事件,但它们的命名有点不同:
- (void)ccTouchesBegan:(NSSet*)touches withEvent:(UIEvent*)event { UITouch* touch = [touches anyObject]; //in your touchesEnded event, you would want to see if you touched //down and then up inside the same place, and do your logic there. }
@david,你的代码有一些关于cocos 0.7.3和2.2.1的拼写错误,特别是CGRectMake而不是CGMakeRect,[touch location]现在是[touch locationInView:touch.view].
这就是我做的:
- (BOOL)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { UITouch * touch = [touches anyObject]; CGPoint location = [[Director sharedDirector] convertCoordinate: [touch locationInView:touch.view]]; CGRect myRect = CGRectMake(sprite.position.x, sprite.position.y, sprite.contentSize.width, sprite.contentSize.height); if(CGRectContainsPoint(myRect, location)) { // particularSprite touched return kEventHandled; } }