This looks weird:
socket.id=Math.random()
I would just use an incrementing number instead:
socket.id = topID++;
From looking at the logic… you receive a keystroke from the client… update the position on the server, and send that new position back to ONLY that client.
I don’t see anywhere where you send the info to the other connected clients.
You’re sending with:
socket.emit('pack',{x:players[socket.id].x,z:players[socket.id].z})
Presumably you will also need to send the socket.id itself to allow the receiver to know which client this is an update for.
I see this in the server code:
players[socket.id]={}
players[socket.id].socket=socket.id
players[socket.id].x=0
players[socket.id].z=0
players[socket.id].walkSpeed=0.2
Instead I would use a pattern like this:
let player = players[socket.id] = {
socket,
x:0,
y:0,
walkSpeed:0.2
}
socket.emit('connected',{id:socket.id}) //Tell the player they connected and what their player ID on the server is...
later when you do the:
socket.emit('pack',{x:players[socket.id].x,z:players[socket.id].z})
instead you want to send this to all the connected clients:
players.forEach(player=> player.socket.emit('pack',{x:player.x,z:player.z,id:player.socket.id});
You’re setInterval is running at 60fps which will probably flood your socket connection when you have more than 1 player. You might want to reduce that to like 10fps…
1000 / 10 instead of 1000/60
On the client side:
socket.on('pack', (e) => {
camera.position.x=e.x
camera.position.z=e.z
});
should instead be something more like:
let players={}
let localPlayerId;
socket.on('connected', (e) => {
//we connected.. and got our server player ID
localPlayerId = e.id;
});
socket.on('pack', (e) => {
//If we haven't seen this player before, create a player and a body for them...
let player=players[e.id] || (players[e.id] = {
});
if( ! player.body )
scene.add(player.body = new THREE.Mesh(new THREE.BoxGeometry()));
//Update the player body position.
player.body.position.x=e.x
player.body.position.z=e.z
if(player.id == localPlayerId){
// We are updating OUR local player.. so update the camera too...
camera.position.copy(player.body.position)
}
});