2

我正在制作一个游戏,其中随机障碍物从屏幕顶部落下,玩家必须避开它们。我在实施删除屏幕下方节点(障碍物)的方法时遇到问题。虽然看起来很简单,但我产生障碍的方式却让人感到困惑。这是我如何产生障碍:

- (void)spawnNewObstacles
{
    //spawn obstacles
    SKSpriteNode *obstacle = [SKSpriteNode spriteNodeWithImageNamed:@"black.png"];

    int position = arc4random() % 320 + 1;
    obstacle.position = CGPointMake(position, 800);
    obstacle.size = CGSizeMake(200, 20);

    obstacle.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:obstacle.frame.size];
    obstacle.physicsBody.dynamic = YES;

    [self addChild:obstacle];
    [obstacles addObject:obstacle]; //obstacles is an NSMutableArray

    [obstacle.physicsBody applyImpulse:CGVectorMake(0, -80.0f)];

    [self performSelector:@selector(spawnNewObstacles) withObject:nil afterDelay:0.25];
}

这就是我尝试(但失败)删除屏幕下方的那些:

-(void)update:(CFTimeInterval)currentTime
{ 
    for(int i=0;i<obstacles.count;i++)
    {
        NSLog(@"Removed an Obstacle"); //this log isn't showing so i concluded that it wasn't working
        SKSpriteNode *obstacle = [obstacles objectAtIndex:i];
        if(obstacle.position.y<0)
        {
            [obstacle removeFromParent];
        }
    }
}

你们会如何建议我这样做?

ps 请用代码解释...

4

1 回答 1

0

从它的声音来看,我猜你还没有用这样obstacles的一行初始化数组:

obstacles = [NSMutableArray array];

设置断点并检查obstacles变量是否为非零。

除此之外,代码看起来还不错。除非您更喜欢使用快速枚举 - 它更安全(索引不会出现越界)、更快且更易于阅读:

for (SKSpriteNode* obstacle in obstacles)
{
    NSLog(@"Removed an Obstacle");
    if (obstacle.position.y < 0)
    {
        [obstacle removeFromParent];
    }
}
于 2014-04-01T15:42:48.017 回答