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

Update method in SpriteKit doesn't update time propely

如果我在更新方法中实现该方法,我想以秒为单位计算它只在第一秒有效,然后它会不停地打印数字,而不会在打印下一个数字之前等待一秒钟; 我不明白为什么会这样

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

        }

不需要为此使用操作; 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

以下是使用 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"];



}

要停止计时器,您可以随时删除与 "counting" 键关联的操作,如下所示:

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