Search code examples
iosobjective-ctiming

iOS timing between taps


I'm trying to keep rhythm between taps. However, I randomly get huge values and I'm not sure why.

@implementation GameScene
{
   CFTimeInterval previousFrameTime;
   SKLabelNode* myLabel;
}

-(void)didMoveToView:(SKView *)view {
   previousTimeFrame = 0.0f;
   myLabel = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];

   myLabel.text = @" ";
   myLabel.fontSize = 12;
   myLabel.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
[self addChild:myLabel];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    myLabel.text = [NSSTring stringWithFormat: @"%f", previousFrameTime];
}

//Called every frame
-(void)update:(CFTimeInterval)currentTime {
    //get the time between frames
    previousFrameTime = CACurrentMediaTime() - previousFrameTime;
}

Output: 0.65323 0.93527 1.65326 5866.42930 <-- ???? 2.52442 5.23156 5888.21345 <-- ?????

What would be causing these random jumps?


Solution

  • This line seems broken to me:

    previousFrameTime = CACurrentMediaTime() - previousFrameTime;

    Let's look at how this would work if you tapped every second, precisely:

    1.) previousFrameTime = 1000 - 0; (1000)
    2.) previousFrameTime = 1001 - 1000; (1)
    3.) previousFrameTime = 1002 - 1; (1001)
    4.) previousFrameTime = 1003 - 1001; (2)