SpriteKit中的更新方法不能正确更新时间

时间:2015-09-14 13:44:38

标签: ios objective-c sprite-kit game-physics game-loop

如果我在更新方法中实现了该方法,我想在几秒内计算它只在第一秒工作,然后它不停地打印数字而不等待一秒钟,然后打印下一个数字; 我不明白为什么会发生这种情况

 -(void) countinSeconds{
            SKAction *count = [SKAction waitForDuration:1];

            SKAction *time = [SKAction runBlock:^{
                    timex++;
                       }];
            SKAction *print = [SKAction runBlock:^{
            NSLog(@"%i",timex);
            }];
            [self runAction:[SKAction sequence:@[count,time,print]]];



        }
        -(void)update:(NSTimeInterval)currentTime {

                    [self countinSeconds];

        }

2 个答案:

答案 0 :(得分:1)

没有必要为此采取行动; update:方法是在当前时间传递的,所以只需要记住你何时开始并做一些简单的数学运算:

@implementation YourClass () {
    BOOL _started;
    NSTimeInterval _startTime;
    NSUInteger _lastLogTime;
}
@end

@implementation YourClass

- (void)update:(NSTimeInterval)currentTime
{
    if (!_started) {
        _startTime = currentTime;
        _started = YES;
    } else {
        NSUInteger elapsedTime = (NSUInteger)(currentTime - _startTime);
        if (elapsedTime != _lastLogTime) {
            NSLog(@"Tick: %lu", elapsedTime);
            _lastLogTime = elapsedTime;
        }
    }
}

@end

答案 1 :(得分:1)

以下是SKAction如何做到这一点:

您不想在update:中运行该方法,而是在其他地方运行,例如在didMoveToView中运行:

-(void)didMoveToView:(SKView *)view {
   [self countinSeconds];
}

此外,你不需要两个街区:

-(void) countinSeconds{


    SKAction *wait = [SKAction waitForDuration:1];

    SKAction *print = [SKAction runBlock:^{
        timex++;
         NSLog(@"%i",timex);
    }];


     [self runAction:[SKAction repeatActionForever:[SKAction sequence:@[wait,print]]] withKey:@"counting"];



}

要停止计时器,您可以随时删除与"计数"相关联的操作。关键,像这样:

if([self actionForKey: @"counting"){[self removeActionForKey:@"counting"];}