Skip to content

Instantly share code, notes, and snippets.

@vgheri
Created December 24, 2012 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vgheri/4369373 to your computer and use it in GitHub Desktop.
Save vgheri/4369373 to your computer and use it in GitHub Desktop.
Handling server updates
function updateGame(updatePacket) {
var goal = false;
if (pongR.game.player1.score() < updatePacket.Game.Player1.Score) {
goal = true;
}
else if (pongR.game.player2.score() < updatePacket.Game.Player2.Score) {
goal = true;
}
var remoteMe = pongR.me.playerNumber === 1 ? updatePacket.Game.Player1 : updatePacket.Game.Player2;
var remoteOther = pongR.me.playerNumber === 2 ? updatePacket.Game.Player1 : updatePacket.Game.Player2;
if (goal) {
pongR.goalTimestamp = new Date().getTime();
// Only update my last processed input id
pongR.me.lastProcessedInputId = remoteMe.LastProcessedInputId
// We also clear history of inputs as we start afresh
pongR.game.player1.score(updatePacket.Game.Player1.Score);
pongR.game.player2.score(updatePacket.Game.Player2.Score);
// Then reset positions
ResetPositionsToInitialState(updatePacket.Game);
// Reset keyboard buffer
keyboard.reset();
performCountdown(3);
}
else {
// Me
updatePlayerState(pongR.me, remoteMe);
// Let's apply client prediction: let's replay all input commands not yet ack'd by the server and check if we have collisions
pongR.me.topLeftVertex = computeNewClientPosition();
checkForCollisionsAndUpdateBallState();
if (pongR.settings.naive_approach) {
// Other - we have to update the score and the latest input id processed!
updatePlayerState(pongR.other, remoteOther);
}
else {
pongR.other.score(remoteOther.Score);
pongR.other.lastProcessedInputId = remoteOther.LastProcessedInputId;
pongR.other.barDirection = remoteOther.BarDirection;
}
pongR.serverUpdates.push(updatePacket);
var tempDate = new Date();
pongR.server_time = tempDate.getUTCTime(updatePacket.Timestamp);
pongR.client_time = pongR.server_time - pongR.settings.net_offset;
//we limit the buffer in seconds worth of updates
//update loop rate * buffer seconds = number of samples
if (pongR.serverUpdates.length >= (66 * pongR.settings.updates_buffer_size)) {
pongR.serverUpdates.splice(0, 1); // remove the oldest item
}
// Ball
updateBallState(updatePacket.Game.Ball);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment