Search code examples
iphoneobjective-ccocos2d-iphonemultiplayer

How to balance start time for a multiplayer game?


I'm making a multiplayer game with GameKit. My issue is that when two devices are connected the game starts running with a slight time difference. On of the devices starts running the game a bit later. But this is not what i want. i want it to start simultaneously on both devices. So the first thing that i do is i check time of the beginning on both devices like this:

startTime = [NSDate timeIntervalSinceReferenceDate];

and this is how it looks:

361194394.193559

Then I send startTime value to the other device and then i compare received value with startTime of the other device.

- (void)balanceTime:(double)partnerTime
{
    double time_diff = startTime - partnerTime;

    if (time_diff < 0)
        startTimeOut = -time_diff;
}

So if difference between two start times is negative it means that this device is starting earlier and therefore it has to wait for exactly the difference assigned to startTimeOut variable, which is a double and usually is something like 2.602417. So then i pause my game in my update method

- (void)update:(ccTime)dt
{   
    if (startTimeOut > 0)
    {
        NSLog(@"START TIME OUT %f", startTimeOut);
        startTimeOut -= dt;
        return;
    }
}

But it unfortunately it doesn't help. Moreover it even extends the difference between start times of the devices. I just can't get why. Seems like everything i'm doing is reasonable. What am i doing wrong? How do i correct it? What would you do? Thanks a lot


Solution

  • As Almo commented, it is not possible to synchronize two devices to the same time. At the lowest level you will gnaw your teeth out on the Heisenberg Uncertainty Principle. Even getting two devices to synchronize to within a tenth of a second is not a trivial task. In addition, time synchronization would have to happen more or less frequently since the clocks in each device run ever so slightly asynchronous (ie a teeny bit faster or a weeny bit slower).

    You also have to consider the lag introduced by sending data over Wifi, Blutooth or over the air. This lag is not a constant, and can be 10ms in one frame and 1000ms in another. You can't cancel out lag, nor can you predict it. But you can predict player movements.

    The solution for games, or at least one of them, is client-side prediction and dead reckoning. This SO question has a few links of interest.