从图层中删除子画面而不删除它(Cocos2d)?

时间:2011-05-24 20:07:07

标签: iphone cocos2d-iphone collision-detection sprite

我在Cocos2d制作游戏。到目前为止,一切都还可以。我使用Ray Wenderlich's教程来使碰撞检测正常工作。它可以工作,但每当一个'敌人'产生子弹被删除的地方(因为被删除的子弹击中目标,因此被删除),敌人也会被自动删除。我认为这是因为它没有删除为精灵声明的rect。注意,即使子弹被删除,它也可以通过多个敌人。任何帮助表示赞赏。谢谢!

编辑: 我发现了问题所在。我在计划中设置了拍摄方法:@selector方法,没有设置间隔。这意味着它可以快速发射子弹60fps。所以我只需点击一下即可获得两颗子弹。他们是如此接近,我花了一段时间才注意到它。我不会再犯那个错误!!!

2 个答案:

答案 0 :(得分:1)

您使用以下代码吗? (来自How To Make A Simple iPhone Game with Cocos2D Tutorial

- (void)update:(ccTime)dt {

  NSMutableArray *projectilesToDelete = [[NSMutableArray alloc] init];
  for (CCSprite *projectile in _projectiles) {
    CGRect projectileRect = CGRectMake(
      projectile.position.x - (projectile.contentSize.width/2), 
      projectile.position.y - (projectile.contentSize.height/2), 
      projectile.contentSize.width, 
      projectile.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(projectileRect, targetRect)) {
        [targetsToDelete addObject:target];             
      }                     
    }

    for (CCSprite *target in targetsToDelete) {
      [_targets removeObject:target];
      [self removeChild:target cleanup:YES];                                    
    }

    if (targetsToDelete.count > 0) {
      [projectilesToDelete addObject:projectile];
    }
    [targetsToDelete release];
  }

  for (CCSprite *projectile in projectilesToDelete) {
    [_projectiles removeObject:projectile];
    [self removeChild:projectile cleanup:YES];
  }
  [projectilesToDelete release];
}
  

每当“敌人”产生子弹被删除的地方时,敌人也会被自动删除。

听起来子弹已从图层中移除,但未从_projectiles数组中删除。

    [_projectiles removeObject:projectile];

您确定此代码有效吗?

答案 1 :(得分:0)

Rect不是您子弹中的单独实体。 Rect是与项目符号关联的属性。一旦你的“子弹被删除”,矩形将不再有效。

您应该关注的是碰撞检查代码。

您可能希望用以下条件包围子弹碰撞检查代码:

if(bullet exists)
{
    check for collision
}

由于您尚未发布代码,我只能在此处发布伪代码。也许如果您发布碰撞检查代码,我可以更详细地向您展示。

相关问题