我正在关注Ray的教程,制作一个简单的iPhone游戏(这里:http://goo.gl/fwPi),并决定我想让敌人在被触摸时被淘汰。
我最初的方法是在触摸位置生成一个小的CCSprite精灵,然后使用CGRectMake创建一个所述精灵的边界框,以检测敌人的精灵是否被触摸。就像雷与射弹/敌人一样。但是,当然,我的做法并不奏效,我无法从这个洞中挖掘出来。
以下是相关的代码段。任何帮助表示赞赏:
- (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]; }
答案 0 :(得分:7)
看起来这是一个非常困难的方法。我自己一直没有编码,但也许以下可能对你有帮助。 假设你有一个名为enemies的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");
}
希望这会有所帮助
答案 1 :(得分:2)
另一种方法是计算触摸位置和精灵之间的距离。如果触摸距离你的一个精灵足够近,你就可以杀死它......就像这样......
for (CCSprite *sprite in anArrayThatCOntainsAllYourSprites) {
float distance = pow(sprite.position.x - location.x, 2) + pow(sprite.position.y - location.y, 2);
distance = sqrt(distance);
if (distance <= 10) {
sprite.dead = YES;
}
}