So I have a node.js / socket.io multiplayer game. And the socket.id get's redefined on the button click.
The .js Script function of the button:
var continueBtn = document.getElementById("continueBtn");
var usernameInput = document.getElementById("usernameInput");
continueBtn.onclick = function(){
if(usernameInput.value != ""){
socket.emit('playerCreated',{
name:usernameInput.value
});
} else {
alert("Username can't be empty");
}
}
The socket.id is set to a random number when a new player connects:
io.sockets.on('connection', function(socket){
console.log('socket connection '+socket.id);
socket.id = Math.random();
//...
}
The responding code to the "playerCreated" socket.emit:
socket.on('playerCreated',function(data){
var player = Player(socket.id, data.name);
SOCKET_LIST[socket.id] = socket;
PLAYER_LIST[socket.id] = player
console.log("Player created with name: \""+PLAYER_LIST[socket.id].name+"\"");
});
Why does my socket.id get reset to a new random number when I create a new player?
++Edit++
I am also running two intervals on the server side:
var isInitialized = false;
setInterval(function(){
if(!isEmpty(PLAYER_LIST)){
var pack = [];
for(var i in PLAYER_LIST){
var player = PLAYER_LIST[i];
player.x++;
player.y++;
pack.push({
x:player.x,
y:player.y
});
}
for(var i in SOCKET_LIST){
var socket = SOCKET_LIST[i];
if(!isInitialized){
if(PLAYER_LIST[socket.id].room === ""){
socket.emit("initialization", {initGrid: initPack.grid})
}else{
socket.to(PLAYER_LIST[socket.id].room).emit("initialization", {initGrid: initPack.grid})
}
isInitialized = true;
}
if(PLAYER_LIST[socket.id].room === ""){
socket.emit("update", {initGrid: initPack.grid})
socket.emit("playerlist", PLAYER_LIST)
}else{
socket.to(PLAYER_LIST[socket.id].room).emit("update", {initGrid: initPack.grid})
}
}
}
},1000/25);
setInterval(() => {
for(var i in SOCKET_LIST){
var socket = SOCKET_LIST[i];
console.log(PLAYER_LIST[socket.id].name +" ### Team: "+PLAYER_LIST[socket.id].team+" ### Role: "+PLAYER_LIST[socket.id].role);
}
}, 2500);