Search code examples
c++cocos2d-iphonecocos2d-xgame-physics

Replay system for cocos2d with FPS correction


I'm building a replay system for my cocos2d-x game, it uses box2d too.

The game is nondeterministic so I can't store the user actions and replay them, so what I'm doing is storing position and angle of a sprite for each time step into a stream.

Now I have replay files that are in the following format

x,y,angle\r\n

Each line represents the state of the sprite at a given time step.

Now when I replay it back on the same device, it's all perfect, but of course life isn't this easy, so the problem arises if i want to play it back on different frame rates, how can this happen ?

is there a smart way to handle this issue ?

I don't have a fixed time step too, I'll implement this soon so you can consider a fixed time step in your answer :)

Thanks !


Solution

  • Ok, you record the delta time along with each recorded frame. Best to start recording the first frame with a delta time of 0 and assume the same for the first frame of the playback.

    Then in your update method accumulate the current delta time:

    -(void) update:(ccTime)delta
    {
        if (firstFrame) 
        {
            totalTime = 0;
            totalRecordedTime = 0;
            firstFrame = NO;
        }
        else
        {
            totalTime += delta;
        }
    
        totalRecordedTime += [self getRecordedDeltaForFrameIndex:recordedFrameIndex];
        if (totalTime > totalRecordedTime)
        {
            [self advanceRecordedFrameIndex];
        }
    
        // alternative:
        id recordedFrameData = [self getRecordedFrameForDeltaTime:totalTime];
        // apply recorded data ...
    }
    

    Alternative: create a method that returns or "applies" the recorded frame based on the current time delta. Pick the frame whose recorded total delta time is equal or lower the current total delta time.

    To make searching for the frame faster, remember the most recent recorded frame's index and start searching from there (compare each frame's delta time), always including the most recent frame as well.

    Occassionally this will display the same recorded frame multiple times, or it may skip recorded frames - depending on the actual device framerate and the framerate during recording.