Multiplayer WebXR Project with Vite/Node/Three.js
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

52 lines
1.5 KiB

const express = require('express');
const http = require('http');
const { Server } = require("socket.io");
const app = express();
const server = http.createServer(app);
const io = new Server(server);
// Serve your existing static files (HTML, JS, CSS)
app.use(express.static(__dirname));
let players = {};
io.on('connection', (socket) => {
console.log('A user connected:', socket.id);
// Create a new player and add them to the players object
players[socket.id] = {
rotation: { x: 0, y: 0, z: 0 },
position: { x: 0, y: 1, z: 0 },
id: socket.id
};
// Send the new player the list of all other players
socket.emit('currentPlayers', players);
// Announce the new player to all other players
socket.broadcast.emit('newPlayer', players[socket.id]);
// Handle player disconnection
socket.on('disconnect', () => {
console.log('User disconnected:', socket.id);
delete players[socket.id];
// Announce the player's disconnection to all other players
io.emit('playerDisconnected', socket.id);
});
// Handle player movement updates
socket.on('playerMovement', (movementData) => {
if (players[socket.id]) {
players[socket.id].position = movementData.position;
players[socket.id].rotation = movementData.rotation;
// Broadcast the movement to all other players
socket.broadcast.emit('playerMoved', players[socket.id]);
}
});
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});