Question: If someone could help me setup multiplayer/socket.io for this game very much appreciated!
First and foremost you need a server.
Like a node.js
with Express
and socket.io
. (so change your template).
After that you create the server file to listen to player moviments and broadcast them.
io.on('connection', (socket) => {
console.log('A user connected:', socket.id);
socket.on('playerMovement', (data) => {
socket.broadcast.emit('otherPlayerMovement', data);
});
socket.on('disconnect', () => {
console.log('User disconnected:', socket.id);
});
})
Doing that you connect your game client to the server (using socket.io) and voilá.
const socket = io.connect('http://localhost:3000');
// For example, you need to emit player's movement to the server
function emitPlayerMovement() {
socket.emit('playerMovement', player);
}
// And listen to movements of other players too
socket.on('otherPlayerMovement', (otherPlayer) => {
// Don't forget to update the game state with otherPlayer data like
player.x = otherPlayer.x;
player.y = otherPlayer.y;
});
This is a base structure just to give you a idea about how to start, so you might need to add some things after to make it a enjoyable experiente for players.
3 Likes