【问题标题】:How to delete nodes that fall below the screen in sprite kit?如何删除精灵套件中落在屏幕下方的节点?
【发布时间】:2014-04-01 15:32:27
【问题描述】:

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

- (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];
        }
    }
}

你们建议我怎么做?

附言请用代码解释...

【问题讨论】:

    标签: objective-c sprite-kit sknode


    【解决方案1】:

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

    obstacles = [NSMutableArray array];
    

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

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

    for (SKSpriteNode* obstacle in obstacles)
    {
        NSLog(@"Removed an Obstacle");
        if (obstacle.position.y < 0)
        {
            [obstacle removeFromParent];
        }
    }
    

    【讨论】:

    • 我也想知道从父节点中删除节点就足够了,或者是否有更好的方法来节省内存
    • 应该够了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多