Networking Multiplayer
Socket.IO Setup
// Server (Node.js)
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const players = {};
io.on('connection', (socket) => {
console.log('Player connected:', socket.id);
players[socket.id] = {
x: 400,
y: 300,
playerId: socket.id
};
socket.emit('currentPlayers', players);
socket.broadcast.emit('newPlayer', players[socket.id]);
socket.on('playerMovement', (movementData) => {
players[socket.id].x = movementData.x;
players[socket.id].y = movementData.y;
socket.broadcast.emit('playerMoved', players[socket.id]);
});
socket.on('disconnect', () => {
delete players[socket.id];
io.emit('playerDisconnected', socket.id);
});
});
server.listen(3000);
Client
class GameScene extends Phaser.Scene {
create() {
this.socket = io('http://localhost:3000');
this.otherPlayers = this.physics.add.group();
this.socket.on('currentPlayers', (players) => {
Object.keys(players).forEach((id) => {
if (id === this.socket.id) {
this.addPlayer(players[id]);
} else {
this.addOtherPlayers(players[id]);
}
});
});
this.socket.on('newPlayer', (playerInfo) => {
this.addOtherPlayers(playerInfo);
});
this.socket.on('playerMoved', (playerInfo) => {
this.otherPlayers.getChildren().forEach((otherPlayer) => {
if (playerInfo.playerId === otherPlayer.playerId) {
otherPlayer.setPosition(playerInfo.x, playerInfo.y);
}
});
});
this.socket.on('playerDisconnected', (playerId) => {
this.otherPlayers.getChildren().forEach((otherPlayer) => {
if (playerId === otherPlayer.playerId) {
otherPlayer.destroy();
}
});
});
}
addPlayer(playerInfo) {
this.player = this.physics.add.sprite(playerInfo.x, playerInfo.y, 'player');
}
addOtherPlayers(playerInfo) {
const otherPlayer = this.physics.add.sprite(playerInfo.x, playerInfo.y, 'otherPlayer');
otherPlayer.playerId = playerInfo.playerId;
this.otherPlayers.add(otherPlayer);
}
update() {
if (this.player) {
const x = this.player.x;
const y = this.player.y;
if (this.player.oldPosition && (x !== this.player.oldPosition.x || y !== this.player.oldPosition.y)) {
this.socket.emit('playerMovement', { x, y });
}
this.player.oldPosition = { x, y };
}
}
}
Best Practices
- Usa interpolazione per movimento fluido
- Limita rate di update (tick rate)
- Server authoritative per anti-cheat
- Predizione client-side
- Compensazione lag
