我正在按照 Ray 的教程制作一个简单的 iPhone 游戏(此处:http://goo.gl/fwPi),并决定我希望敌人在被触摸时被消灭。
我最初的方法是在触摸位置生成一个小的 CCSprite Sprite ,然后使用 CGRectMake 为所述 Sprite 创建一个边界框以检测敌人 Sprite 是否被触摸。就像雷对射弹/敌人所做的一样。但当然,我的方法行不通,我无法摆脱困境。
这是相关的代码片段。任何帮助表示赞赏:
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { // Choose one of the touches to work with UITouch *touch = [touches anyObject]; CGPoint location = [self convertTouchToNodeSpace: touch]; location = [[CCDirector sharedDirector] convertToGL:location]; CCSprite *touchedarea = [CCSprite spriteWithFile:@"Icon-72.png" rect:CGRectMake(location.x, location.y, 2, 2)]; touchedarea.tag = 2; [self addChild:touchedarea]; [_touchedareas addObject:touchedarea]; } - (void)update:(ccTime)dt { NSMutableArray *touchedareasToDelete = [[NSMutableArray alloc] init]; for (CCSprite *touchedarea in _touchedareas) { CGRect touchedareaRect = CGRectMake( touchedarea.position.x, touchedarea.position.y, touchedarea.contentSize.width, touchedarea.contentSize.height); NSMutableArray *targetsToDelete = [[NSMutableArray alloc] init]; for (CCSprite *target in _targets) { CGRect targetRect = CGRectMake( target.position.x - (target.contentSize.width/2), target.position.y - (target.contentSize.height/2), target.contentSize.width, target.contentSize.height); if (CGRectIntersectsRect(touchedareaRect, targetRect)) { [targetsToDelete addObject:target]; } } for (CCSprite *target in targetsToDelete) { [_targets removeObject:target]; [self removeChild:target cleanup:YES]; } if (targetsToDelete.count > 0) { [touchedareasToDelete addObject:touchedarea]; } [targetsToDelete release]; } for (CCSprite *touchedarea in touchedareasToDelete) { [_touchedareas removeObject:touchedarea]; [self removeChild:touchedarea cleanup:YES]; } [touchedareasToDelete release]; }
最佳答案
这看起来是一种非常困难的方法。我自己的编码时间不长,但也许以下内容可能对您有所帮助。 假设你有一个名为 enemys 的 nsmutablearray,当你创建一个敌人时,你将新的敌人对象添加到这个数组中。敌人对象将是一个 ccnode 并在其中包含一个名为 _enemySprite 的 ccsprite 然后触摸
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSSet *allTouches = [event allTouches];
UITouch * touch = [[allTouches allObjects] objectAtIndex:0];
//UITouch* touch = [touches anyObject];
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
int arraysize = [enemies count];
for (int i = 0; i < arraysize; i++) {
if (CGRectContainsPoint( [[[enemies objectAtIndex:i] _enemySprite] boundingBox], location)) {
//some code to destroy ur enemy here
}
}
// NSLog(@"TOUCH DOWN");
}
希望对你有帮助
关于iphone - 检测是否在 Cocos2d-iphone 上触摸了特定的 Sprite ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4704538/