Skip to content

Instantly share code, notes, and snippets.

@wolf81
Last active May 8, 2021 15:11
Show Gist options
  • Save wolf81/b16dbd35c59a13a60e18d02c95b20523 to your computer and use it in GitHub Desktop.
Save wolf81/b16dbd35c59a13a60e18d02c95b20523 to your computer and use it in GitHub Desktop.
Jitter buffer
local CLIENT_BUFFER_SIZE = 3
local client = Class { __includes = Peer }
function client:onConnect(data) --[[ ... ]] end
function client:onDisconnect(data) --[[ ... ]] end
function client:onStart(state) --[[ ... ]] end
function client:onStop(message) --[[ ... ]] end
function client:onPaddleId(paddleId) --[[ ... ]] end
function client:onUpdate(state)
self.buffer:enqueue(state)
-- wait for buffer to be full, before starting updates
if self.buffer:isFull() then self.isUpdating = true end
end
function client:init(host, port, control)
Peer.init(self, host, port, PEER_MODE_CLIENT)
self.updated = function () end
self.started = function () end
self.disconnected = function() end
self.control = control
self.state = State()
self.paddleId = nil
self.buffer = Buffer(CLIENT_BUFFER_SIZE, function(state1, state2) return state1.tick > state2.tick end)
self.updateTimer = nil
self.isUpdating = false
self:registerMessageHandler(NET_MESSAGE_CONNECT, function(data) self:onConnect(data) end)
self:registerMessageHandler(NET_MESSAGE_DISCONNECT, function(data) self:onDisconnect(data) end)
self:registerMessageHandler(NET_MESSAGE_STOP, function(message) self:onStop(message) end)
self:registerMessageHandler(NET_MESSAGE_PADDLE_ID, function(paddleId) self:onPaddleId(paddleId) end)
self:registerMessageHandler(NET_MESSAGE_START, function(state) self:onStart(state) end)
self:registerMessageHandler(NET_MESSAGE_UPDATE, function(state) self:onUpdate(state) end)
end
function client:connect()
printf("[client] connect ...")
Peer.start(self)
end
function client:disconnect()
printf("[client] disconnect ...")
Peer.stop(self)
self.paddleId = nil
end
function client:update(dt)
Peer.update(self, dt)
if not self.paddleId then return end
-- check for player input, send to server
local direction = self.control:update(dt, self.paddleId, self.state)
self:send(NET_MESSAGE_MOVE, direction)
if self.control:getAttack() then self:send(NET_MESSAGE_ATTACK) end
-- if buffer is empty, wait for buffer to refill
if self.buffer:isEmpty() then self.isUpdating = false end
-- if buffer is not empty, proceed to next state
if self.isUpdating == true then self.state = self.buffer:dequeue() end
end
function client:keypressed(key, code)
self.control:keypressed(key, code)
end
function client:keyreleased(key, code)
self.control:keyreleased(key, code)
end
return client
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment