Recently i try to create an multiplayer application and I already go through the playcanvas real-time multiplayer tutorial. I trying to create a game that only two people can play at the same time, so I use the socket.io room function to automatically allocate client to an empty room. If the room already has two client then the next client will automatically join another empty room. But even though the clients not in the same room but they still able to see each other. So what I do wrong in the code?
this is the code in playcanvas
var Network = pc.createScript('network');
// static variables
Network.id = null;
Network.socket = null;
var newPlayer=[];
// initialize code called once per entity
Network.prototype.initialize = function() {
this.player = this.app.root.findByName('Player');
this.other = this.app.root.findByName('Other');
var socket = io.connect('https://tungsten-rhinestone-sweatshirt.glitch.me'); // Glitch hosted server
Network.socket = socket;
socket.emit ('initialize');
var self = this;
socket.on ('playerData', function (data) {
self.initializePlayers (data);
console.log(data.roomNo);
});
socket.on ('playerJoined', function (data) {
self.addPlayer(data);
});
socket.on ('playerMoved', function (data) {
self.movePlayer(data);
});
socket.on ('killPlayer', function (data) {
self.removePlayer(data);
});
};
Network.prototype.initializePlayers = function (data) {
this.players = data.players;
Network.id = data.id;
this.players.room=data.roomNo;
for(var id in this.players){
if(id != Network.id){
this.players[id].entity = this.createPlayerEntity(this.players[id]);
}
}
// console.log(this.players.room);
this.initialized = true;
};
Network.prototype.addPlayer = function (data) {
this.players[data.id] = data;
this.players[data.id].entity = this.createPlayerEntity(data);
};
Network.prototype.movePlayer = function (data) {
if (this.initialized && !this.players[data.id].deleted) {
this.players[data.id].entity.rigidbody.teleport(data.x, data.y, data.z);
}
};
Network.prototype.removePlayer = function (data) {
if (this.players[data].entity) {
this.players[data].entity.destroy ();
this.players[data].deleted = true;
}
};
Network.prototype.createPlayerEntity = function (data) {
//if(newPlayer[data.roomNo]===this.players[data.roomNo])
{
newPlayer = this.other.clone();
newPlayer.enabled = true;
this.other.getParent().addChild(newPlayer);
if (data)
newPlayer.rigidbody.teleport(data.x, data.y, data.z);
return newPlayer;}
};
// update code called every frame
Network.prototype.update = function(dt) {
this.updatePosition();
};
Network.prototype.updatePosition = function () {
if (this.initialized) {
var pos = this.player.getPosition();
Network.socket.emit('positionUpdate', {id: Network.id, x: pos.x, y: pos.y, z: pos.z});
}
};
below is the url link to my server:
Sincerely Elliot.