-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
286 lines (248 loc) · 7.85 KB
/
server.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
const express = require("express");
const { createServer } = require("http");
const { Server } = require("socket.io");
const app = express();
const server = createServer(app);
const io = new Server(server);
let players = {};
let bullets = {};
let walls = {};
const spawnPoints = [[250, 2100], [2650, 2100], [1450, 2100], [1450, 250], [1450, 3950]];
const bulletSpeed = 10;
const playerLength = 70;
let timings = {
updatePlayer: { count: 0, total: 0 },
updateBullets: { count: 0, total: 0 },
};
function startTiming() {
return process.hrtime();
}
function endTiming(startTime) {
const diff = process.hrtime(startTime);
return diff[0] * 1e3 + diff[1] / 1e6; // convert to milliseconds
}
setInterval(() => {
console.log("Performance metrics (last second):");
console.log(`Player updates: ${timings.updatePlayer.count} times, average time: ${timings.updatePlayer.count ? (timings.updatePlayer.total / timings.updatePlayer.count).toFixed(2) : 0} ms`);
console.log(`Bullet updates: ${timings.updateBullets.count} times, average time: ${timings.updateBullets.count ? (timings.updateBullets.total / timings.updateBullets.count).toFixed(2) : 0} ms`);
// Reset counters
timings.updatePlayer.count = 0;
timings.updatePlayer.total = 0;
timings.updateBullets.count = 0;
timings.updateBullets.total = 0;
}, 1000);
// io connections
io.on("connection", (socket) => {
console.log("SERVER: socket", socket.id, "connected");
io.emit("notification", socket.id + " connected");
// Handle ping-pong
socket.on('ping', (timestamp) => {
socket.emit('pong', timestamp);
});
// updates the player
socket.on("serverUpdateSelf", (playerData) => {
const startTime = startTiming();
if (players[playerData.id]) {
if (players[playerData.id].health <= 0) {
let spawnPoint = bestSpawnPoint();
players[playerData.id] = {
...playerData,
health: 100,
x: spawnPoint[0],
y: spawnPoint[1]
};
return;
}
} else {
let spawnPoint = bestSpawnPoint();
players[playerData.id] = {
...playerData,
health: 100,
x: spawnPoint[0],
y: spawnPoint[1]
};
return;
}
let speed = 3; // player speed
if (playerData.keyboard.shift) {
speed += 1.5;
}
const player = players[playerData.id];
const playerBounds = {
x: player.x,
y: player.y,
width: playerLength,
height: playerLength,
};
let canMoveUp = true;
let canMoveLeft = true;
let canMoveDown = true;
let canMoveRight = true;
// Check potential collisions with walls before moving
Object.entries(walls).forEach(([wallId, wall]) => {
if (checkCollision(wall, { ...playerBounds, y: playerBounds.y - speed })) {
canMoveUp = false;
}
if (checkCollision(wall, { ...playerBounds, x: playerBounds.x - speed })) {
canMoveLeft = false;
}
if (checkCollision(wall, { ...playerBounds, y: playerBounds.y + speed })) {
canMoveDown = false;
}
if (checkCollision(wall, { ...playerBounds, x: playerBounds.x + speed })) {
canMoveRight = false;
}
});
if (playerData.keyboard.w && canMoveUp) {
player.y -= speed;
}
if (playerData.keyboard.a && canMoveLeft) {
player.x -= speed;
}
if (playerData.keyboard.s && canMoveDown) {
player.y += speed;
}
if (playerData.keyboard.d && canMoveRight) {
player.x += speed;
}
// Check collision between bullet and player
Object.entries(bullets).forEach(([bulletId, bullet]) => {
if (bullet.parent_id !== socket.id) { // if the bullet isn't fired from the same person check collision
if (checkCollision(bullet, playerBounds)) {
players[playerData.id].health -= 10;
delete bullets[bulletId];
if (players[playerData.id].health <= 0) {
console.log(bullet.parent_username + " killed " + playerData.username);
io.emit("notification", bullet.parent_username + " killed " + playerData.username);
socket.emit("clientUpdateSelf", players[playerData.id]);
return;
}
}
}
});
// Check collision between wall and bullet
Object.entries(walls).forEach(([wallId, wall]) => {
Object.entries(bullets).forEach(([bulletId, bullet]) => {
if (checkCollision(wall, bullet)) {
delete bullets[bulletId];
}
});
});
players[playerData.id] = {
...playerData,
health: players[playerData.id].health,
x: player.x,
y: player.y
};
socket.emit("clientUpdateSelf", players[playerData.id]);
const elapsed = endTiming(startTime);
timings.updatePlayer.count++;
timings.updatePlayer.total += elapsed;
});
socket.on("serverUpdateNewBullet", (bullet) => {
if (
players[socket.id] &&
players[socket.id].hasOwnProperty("health") &&
players[socket.id].health <= 0
) {
return;
}
bullets[bullet.id] = bullet;
io.emit("clientUpdateNewBullet", bullet);
});
socket.on('addWall', (wallData) => {
walls[wallData.id] = wallData;
});
socket.on("disconnect", () => {
console.log("SERVER: socket", socket.id, "disconnected");
io.emit("notification", socket.id + " disconnected");
delete players[socket.id];
});
});
// Sending x every y seconds
// Send all player data to clients every 10ms excluding the player's own data
setInterval(() => {
for (const playerSocketId in players) {
const enemies = { ...players };
delete enemies[playerSocketId];
if (enemies[playerSocketId]) {
if (enemies[playerSocketId].health <= 0) {
delete enemies[playerSocketId];
}
}
// Emit the updated data to the current player
io.to(playerSocketId).emit("clientUpdateAllEnemies", enemies);
}
}, 10);
// Calculate bullet trajectory (server side) (200 times per second)
setInterval(() => {
const startTime = startTiming();
if (Object.keys(bullets).length === 0) {
return;
}
for (const bulletId in bullets) {
const bullet = bullets[bulletId];
bullet.x += Math.cos(bullet.rotation) * bulletSpeed;
bullet.y += Math.sin(bullet.rotation) * bulletSpeed;
if (
bullet.x > 5000 ||
bullet.x < -5000 ||
bullet.y > 5000 ||
bullet.y < -5000
) {
delete bullets[bulletId];
}
}
io.emit("clientUpdateAllBullets", bullets);
const elapsed = endTiming(startTime);
timings.updateBullets.count++;
timings.updateBullets.total += elapsed;
}, 2);
// check for disconnected players and remove them
setInterval(() => {
for (const playerSocketId in players) {
if (playerSocketId === "undefined") {
delete players[playerSocketId];
}
}
}, 1500);
// HELPER FUNCTIONS
function checkCollision(aBox, bBox) {
return (
aBox.x < bBox.x + bBox.width &&
aBox.x + aBox.width > bBox.x &&
aBox.y < bBox.y + bBox.height &&
aBox.y + aBox.height > bBox.y
);
}
// spawn player based on the spawn points farthest from other players
function bestSpawnPoint() {
if (Object.keys(players).length === 0) {
return spawnPoints[Math.floor(Math.random() * spawnPoints.length)];
}
let maxDistance = 0;
let bestSpawnPoint = spawnPoints[0];
spawnPoints.forEach((spawnPoint) => {
let minDistance = Infinity;
Object.values(players).forEach((player) => {
const distance = Math.sqrt(
Math.pow(player.x - spawnPoint[0], 2) + Math.pow(player.y - spawnPoint[1], 2)
);
if (distance < minDistance) {
minDistance = distance;
}
});
if (minDistance > maxDistance) {
maxDistance = minDistance;
bestSpawnPoint = spawnPoint;
}
});
return bestSpawnPoint;
}
// final setup
const PORT = process.env.PORT || 8080;
app.use(express.static("public"));
app.use("/pixi", express.static("./node_modules/pixi.js/dist/"));
server.listen(PORT, () => {
console.log("SERVER STARTED");
});