Search code examples
iosobjective-csprite-kitgame-physicsgame-loop

Update method in SpriteKit doesn't update time propely


i want to count in seconds if i implemented the method in the update method it only works for the first second then it keeps printing number non stop without waiting for one second before printing the next number; i don't understand why this is happening

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

        }

Solution

  • There is no need to use actions for this; the update: method is passed the current time, so it's simply a matter of remembering when you started and doing some simple maths:

    @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