Network Game Latency

A simple implementation to get around client-side prediction in games and networking.

by Sam Fereday

JavaScript

// http://www.gabrielgambetta.com/fpm2.html
// Dumb - Controlled by server after input
var Client = function(){};
Client.prototype = {
    x: 0,
    y: 0,
    server: null,
	tell: function(data){
    	if(data) console.log("Original client got response from server, result was valid.", this.x, this.y);
    },
    changePosition: function(x, y) {
        // So in this example, we move the character 1 to the right.
		this.x = x;
        this.y = y;
        console.log("Client changing position to:", x, y);
        // We send this to the server, then do the animation anyway
        console.log("Client informing server of change.");
        // The server will return what 'hopefully' is the right command, but has updated other players in the meantime
        tellServer(x, y);
        console.log("Clients new position:", this.x, this.y);
    }
}

// Authoritive - Server that determines where client shall be.
var Server = function(){};
Server.prototype = {
    client: null, // We'd obviously have more than one client.
    connect: function(client) {
    	client.server = this;
        this.client = client;
    },
	tell: function(x, y){
    	console.log("Server got data, client should already be updating local position at this point.");
        this.client.tell( this.setPosition(x, y) );
    },
    setPosition: function(x, y){
    	// If position seems valid, then return true.
        console.log("Server sets own client position (and tells other clients):", x, y);
    	return true;
    }
}

// Do a thing
var client = new Client();
var server = new Server();
server.connect(client); // We wouldn't do it this way really, but it's just a test. Don't forget also, we would NEVER pass the client object across the network. It just needs to know that a user wants to connect. We'd actually create a client on the server its self, then just return position info and not much else. Carry on.
client.changePosition(1, 0);

// Fake transfer
function tellServer(x, y)...