-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
63 lines (56 loc) · 1.78 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const express = require("express");
const socketIo = require("socket.io");
const http = require("http");
const PORT = process.env.PORT || 5000;
const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
cors: {
origin: "*",
},
}); //in case server and client run on different urls
let players = [];
io.on("connection", (socket) => {
console.log("new connexion:", socket.id);
socket.join("room");
socket.on("setupPlayer", (data) => {
console.log("setupPlayer data :", data);
const newPlayer = {
id: socket.id,
position: data.position,
anim: data.anim,
flipX: false,
};
players.push(newPlayer);
console.log("added player :", newPlayer);
const otherPlayers = players.filter((player) => {
return player.id !== socket.id;
});
socket.emit("initialPlayers", otherPlayers);
socket.broadcast.to("room").emit("playerJoin", newPlayer);
});
socket.on("disconnect", () => {
players = [...players].filter((player) => player.id !== socket.id);
io.to("room").emit("playerLeave", socket.id);
});
socket.on("updatePlayer", (data) => {
const updatedPlayer = { ...data, id: socket.id };
//console.log("player ask for update:", updatedPlayer);
players.forEach((player) => {
if (player.id === updatedPlayer.id) {
player.position = updatedPlayer.position;
player.anim = updatedPlayer.anim;
player.flipX = updatedPlayer.flipX;
}
});
//console.log("Updated players : ", players);
socket.broadcast.to("room").emit("updatePlayer", updatedPlayer);
});
socket.on("newMessage", (data) => {
io.to("room").emit("newMessage", data);
});
});
server.listen(PORT, (err) => {
if (err) console.log(err);
console.log("Server running on Port ", PORT);
});