I am trying to use Box2d on nodejs server with libGDX client. What I am trying to apply is authoritative server model so clients are just sending input data to server, server is running simulation and returning data to clients.
Client sends right key pressed input data to server, server calculates applyForce vector, applies force to server side body.
Server is sending world's body data to clients such as linearVelocity, position angular velocity etc with sendWorldData()
function. After geting data, clients equalize this data to client side bodies.
Right now I just equalize linear velocity data, if I use setTransform
on body for same position, it breaks the simulation and game crashes. I guess just linear velocity is way to go for now.
The problem is: even though I return the same linearvelocity from server to client, bodies end up on slightly different x,y
positions.
client is
(6.8612046,7.3647866)
server is
(7.260152142360204,7.807573379341183)
I read a lot about this problem and started by trying to fix timestep on server and client. Client timestep:
private var fixedTimestepAccumulator = 0f
private var MAX_ACCUMULATED_TIME = 1.0f
val TIMESTEP = 1 / 60f
fun update(delta:Float){
fixedTimestepAccumulator += delta;
if(fixedTimestepAccumulator > MAX_ACCUMULATED_TIME)
fixedTimestepAccumulator = MAX_ACCUMULATED_TIME;
while (fixedTimestepAccumulator >= TIMESTEP) {
world.step(TIMESTEP, 6, 2);
fixedTimestepAccumulator -= TIMESTEP;
}
inputUpdate(delta)
cameraUpdate(delta)
tmr.setView(camera)
batch.projectionMatrix.set(camera.combined)
}
Server update method:
var lastUpdate = Date.now()/1000;
var fixedTimestepAccumulator = 0;
var MAX_ACCUMULATED_TIME = 1;
var TIMESTEP = 1/60;
function physics_hanlder() {
var now = Date.now() / 1000;
var delta = now - lastUpdate;
lastUpdate = now;
fixedTimestepAccumulator = fixedTimestepAccumulator+delta;
if(fixedTimestepAccumulator > MAX_ACCUMULATED_TIME)
fixedTimestepAccumulator = MAX_ACCUMULATED_TIME;
while (fixedTimestepAccumulator >= TIMESTEP) {
world.step(TIMESTEP,6,2);
sendWorldData() // sends servers body data to clients
fixedTimestepAccumulator -= TIMESTEP;
}
}
setInterval(physics_hanlder, 1000/60);