-
Notifications
You must be signed in to change notification settings - Fork 1
/
Latest.ts
590 lines (525 loc) · 14.1 KB
/
Latest.ts
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
import { emitter } from "@/composables/useEmit";
import type { User } from "@/types/general";
const characterAnimations: {
[key: string]: number[][];
} = {
"walk-down": [
[0, 0],
[24, 1],
[48, 0],
],
"walk-left": [
[0, 24],
[24, 25],
[48, 24],
],
"walk-right": [
[0, 48],
[24, 49],
[48, 48],
],
"walk-up": [
[0, 72],
[24, 73],
[48, 72],
],
};
function loadImage(src: string): HTMLImageElement {
const image = new Image();
image.src = src;
return image;
}
function drawPlayer(
ctx: CanvasRenderingContext2D,
characterImg: HTMLImageElement,
animation: string,
frame: number,
player: User,
cameraX: number,
cameraY: number,
zoomFactor: number,
userStatus: string,
isMouseOver: boolean
) {
// Draw shadow
const shadowX = (player.x - cameraX - 8) * zoomFactor;
const shadowY = (player.y - cameraY - 8) * zoomFactor;
const shadowRadius = 30 * zoomFactor;
ctx.fillStyle = "rgba(200, 200, 200, 0.5)";
ctx.beginPath();
ctx.arc(
shadowX + 48 * zoomFactor,
shadowY + 80 * zoomFactor,
shadowRadius,
0,
2 * Math.PI
);
ctx.closePath();
// Draw shadow border
ctx.strokeStyle = "rgba(255, 255, 255, 0.5)";
ctx.lineWidth = 4 * zoomFactor;
ctx.beginPath();
ctx.arc(
shadowX + 48 * zoomFactor,
shadowY + 80 * zoomFactor,
shadowRadius,
0,
2 * Math.PI
);
ctx.closePath();
if (isMouseOver) {
ctx.fill();
ctx.stroke();
}
// Draw character
const frameCoords = characterAnimations[animation][frame];
ctx.drawImage(
characterImg,
frameCoords[0],
frameCoords[1],
24,
24,
shadowX,
shadowY,
96 * zoomFactor,
96 * zoomFactor
);
// Draw player name background
ctx.fillStyle = "rgba(0, 0, 0, 0.5)";
ctx.font = `${14 * zoomFactor}px Poppins`;
const userNameTextWidth = ctx.measureText(player.userName).width;
const padding = 15 * zoomFactor;
const backgroundHeight = 20 * zoomFactor;
const backgroundWidth = userNameTextWidth + padding * 3;
const backgroundX = (player.x - cameraX - userNameTextWidth / 24) * zoomFactor;
const backgroundY = (player.y - cameraY - characterImg.height / 4) * zoomFactor;
ctx.beginPath();
ctx.arc(
backgroundX + backgroundHeight / 2,
backgroundY + backgroundHeight / 2,
backgroundHeight / 2,
Math.PI / 2,
(3 * Math.PI) / 2
);
ctx.arc(
backgroundX + backgroundWidth - backgroundHeight / 2,
backgroundY + backgroundHeight / 2,
backgroundHeight / 2,
(3 * Math.PI) / 2,
Math.PI / 2
);
ctx.closePath();
ctx.fill();
// Draw user status icon
const statusRadius = 5 * zoomFactor;
const statusX = backgroundX + padding;
const statusY = backgroundY + backgroundHeight / 2;
switch (userStatus) {
case "online":
ctx.fillStyle = "#2CC56F";
break;
case "busy":
ctx.fillStyle = "orange";
break;
case "away":
ctx.fillStyle = "gray";
break;
default:
ctx.fillStyle = "gray";
}
ctx.beginPath();
ctx.arc(statusX, statusY, statusRadius, 0, 2 * Math.PI);
ctx.fill();
// Draw player name
ctx.fillStyle = "white";
ctx.fillText(
player.userName,
(player.x - cameraX) * zoomFactor + 10 + padding,
(player.y - cameraY - characterImg.height / 11) * zoomFactor
);
}
function updateAnimationFrame(
pressedKeys: { [key: string]: boolean },
animationState: string,
animationFrame: number,
animationTick: number
): [number, number] {
if (pressedKeys.w || pressedKeys.a || pressedKeys.s || pressedKeys.d) {
animationTick++;
} else {
animationFrame = 1;
}
if (animationTick >= 7) {
animationFrame++;
if (animationFrame >= characterAnimations[animationState].length) {
animationFrame = 0;
}
animationTick = 0;
}
return [animationFrame, animationTick];
}
function isColliding(
rect1: { x: number; y: number; width: number; height: number },
rect2: { x: number; y: number; width: number; height: number }
): boolean {
return (
rect1.x < rect2.x + rect2.width &&
rect1.x + rect1.width > rect2.x &&
rect1.y < rect2.y + rect2.height &&
rect1.y + rect1.height > rect2.y
);
}
export function createCanvasApp(
users: User[],
myPlayerId: string,
speed: number,
canvas: HTMLCanvasElement,
canvasFrameRate: number,
spaceMap: string,
myCharacterSprite: string,
initialSetupCompleted: boolean
) {
const ctx = canvas.getContext("2d")!;
const worldImg = loadImage(spaceMap);
const characterImg = loadImage(myCharacterSprite);
const characterImgMyPlayer = loadImage(myCharacterSprite);
let cameraX = 200;
let cameraY = 200;
let myPlayer: User = {
id: "",
userName: "",
x: 0,
y: 0,
characterSprite: "",
facingTo: "",
userStatus: "",
};
// When the user releases right key while still pressing the up key, character should start going up
let keyPressOrder: string[] = [];
const pressedKeys: {
[key: string]: boolean;
} = {
w: false,
a: false,
s: false,
d: false,
};
let zoomFactor = 1;
let animationState = "walk-down";
let animationFrame = 0;
let animationTick = 0;
let lastTime = performance.now();
let fps = 0;
let refreshInterval = 1000 / canvasFrameRate;
const userAgent = navigator.userAgent;
let mouseX = 0;
let mouseY = 0;
canvas.addEventListener("mousemove", (e: MouseEvent) => {
mouseX = e.clientX;
mouseY = e.clientY;
});
const gameLoop = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Center camera on my player
myPlayer = users.find((user) => user.id === myPlayerId)!;
if (myPlayer) {
cameraX = myPlayer?.x - canvas.width / (2.2 * zoomFactor);
cameraY = myPlayer.y - canvas.height / (2.2 * zoomFactor);
// Draw world
ctx.drawImage(
worldImg,
0,
0,
worldImg.width,
worldImg.height,
(-cameraX - worldImg.height / 2) * zoomFactor,
(-cameraY - worldImg.width / 2) * zoomFactor,
worldImg.width * zoomFactor,
worldImg.height * zoomFactor
);
// Move my player but only if no other key is pressed(prevent diagonal movement). Also, if the user releases the second pressed key, the character should continue moving in the direction of the first pressed key
if (keyPressOrder.length > 0) {
let newPlayerX = myPlayer.x;
let newPlayerY = myPlayer.y;
const lastValidKey = keyPressOrder[keyPressOrder.length - 1];
switch (lastValidKey) {
case "w":
newPlayerY -= speed;
animationState = "walk-up";
break;
case "a":
newPlayerX -= speed;
animationState = "walk-left";
break;
case "s":
newPlayerY += speed;
animationState = "walk-down";
break;
case "d":
newPlayerX += speed;
animationState = "walk-right";
break;
}
// Check for collisions
const playerWidth = 64 * zoomFactor;
const playerHeight = 64 * zoomFactor;
let collision = false;
for (const user of users) {
if (
user.id !== myPlayerId &&
isColliding(
{
x: newPlayerX,
y: newPlayerY,
width: playerWidth,
height: playerHeight,
},
{ x: user.x, y: user.y, width: playerWidth, height: playerHeight }
)
) {
collision = true;
break;
}
}
if (!collision) {
myPlayer.x = newPlayerX;
myPlayer.y = newPlayerY;
}
}
// Draw other players
users.forEach((user) => {
if (user.id !== myPlayerId) {
const playerRect = {
x: (user.x - cameraX - 8) * zoomFactor,
y: (user.y - cameraY - 8) * zoomFactor,
width: 96 * zoomFactor,
height: 96 * zoomFactor,
};
const isMouseOver = isColliding(
{ x: mouseX, y: mouseY, width: 1, height: 1 },
playerRect
);
drawPlayer(
ctx,
characterImg,
"walk-down",
1,
user,
cameraX,
cameraY,
zoomFactor,
user.userStatus,
isMouseOver
);
}
});
// Draw my player
const playerRect = {
x: (myPlayer.x - cameraX - 8) * zoomFactor,
y: (myPlayer.y - cameraY - 8) * zoomFactor,
width: 96 * zoomFactor,
height: 96 * zoomFactor,
};
const isMouseOver = isColliding(
{ x: mouseX, y: mouseY, width: 1, height: 1 },
playerRect
);
drawPlayer(
ctx,
characterImgMyPlayer,
animationState,
animationFrame,
myPlayer,
cameraX,
cameraY,
zoomFactor,
myPlayer.userStatus,
isMouseOver
);
// Update animation frame
[animationFrame, animationTick] = updateAnimationFrame(
pressedKeys,
animationState,
animationFrame,
animationTick
);
}
// Calculate FPS
const currentTime = performance.now();
const deltaTime = currentTime - lastTime;
lastTime = currentTime;
// Draw FPS
fps = Math.round(1000 / deltaTime);
ctx.fillStyle = "black";
// Bold Poppins 16px
ctx.font = "bold 16px Poppins";
ctx.fillText(`FPS: ${fps}`, 10, 20);
// Check the browser and use the appropriate fps limiter because every browser has its own way of doing it
if (userAgent.indexOf("Firefox") > -1) {
// FIXME: Can't limit fps in Firefox
requestAnimationFrame(gameLoop);
} else if (userAgent.indexOf("Chrome") > -1) {
setTimeout(gameLoop, refreshInterval);
} else {
setTimeout(gameLoop, refreshInterval);
}
};
if (
users.length > 0 &&
myPlayerId !== "" &&
speed !== 0 &&
spaceMap !== "" &&
initialSetupCompleted
) {
gameLoop();
} else {
const checkConditionsBeforeLoop = setInterval(() => {
if (
users.length > 0 &&
myPlayerId !== "" &&
speed !== 0 &&
spaceMap !== "" &&
initialSetupCompleted
) {
gameLoop();
clearInterval(checkConditionsBeforeLoop);
// Emit event to notify that the canvas is loaded
emitter.emit("canvasLoaded");
}
}, 0);
}
/******************
* KEYBOARD EVENTS *
******************/
// Check if only one key is pressed
canvas.addEventListener("keydown", (e: KeyboardEvent) => {
const key = e.key.toLowerCase();
if (["w", "a", "s", "d"].includes(key) && !pressedKeys[key]) {
keyPressOrder.push(key);
}
// Listen to both lower and upper case
switch (e.key.toLowerCase()) {
case "w":
pressedKeys.w = true;
break;
case "a":
pressedKeys.a = true;
break;
case "s":
pressedKeys.s = true;
break;
case "d":
pressedKeys.d = true;
break;
}
// TODO: In the close future, we may want to emit other users moving as well. For now, we only emit my player moving
/*
const validKeys = ["w", "a", "s", "d"];
if (validKeys.includes(key)) {
// Emit player move event
emitter.emit("playerMove", myPlayer);
} */
emitter.emit("closeRightClickMenu");
});
canvas.addEventListener("keyup", (e: KeyboardEvent) => {
const key = e.key.toLowerCase();
switch (key) {
case "w":
pressedKeys.w = false;
break;
case "a":
pressedKeys.a = false;
break;
case "s":
pressedKeys.s = false;
break;
case "d":
pressedKeys.d = false;
break;
}
// Only emit if key is w,a,s,d or W,A,S,D and after user has stopped moving
const validKeys = ["w", "a", "s", "d"];
if (validKeys.includes(key)) {
// Emit player move event
emitter.emit("playerMove", myPlayer);
}
keyPressOrder = keyPressOrder.filter((k) => k !== key);
});
/******************
* MOUSE EVENTS *
******************/
// Listen to double click
/* canvas.addEventListener("dblclick", (e: MouseEvent) => {
const x = e.clientX + cameraX - 8;
const y = e.clientY + cameraY - 25;
// Emit double click event
emitter.emit("doubleClick", { x, y });
myPlayer.x = x;
myPlayer.y = y;
}); */
// Listen to right click
canvas.addEventListener("contextmenu", (e: MouseEvent) => {
const mouseX = e.clientX;
const mouseY = e.clientY;
const worldX = e.clientX + cameraX;
const worldY = e.clientY + cameraY;
const mousePos = {
mouseX,
mouseY,
};
const worldPos = {
worldX,
worldY,
};
// Check if the right-click is on any user, if so, don't emit right click event
const playerWidth = 64 * zoomFactor;
const playerHeight = 64 * zoomFactor;
let collision = false;
for (const user of users) {
// Check for collisions
if (
user.id !== myPlayerId &&
isColliding(
{
x: worldX - 36,
y: worldY - 64,
width: playerWidth,
height: playerHeight,
},
{ x: user.x, y: user.y, width: playerWidth, height: playerHeight }
)
) {
collision = true;
break;
}
}
// Only update position if there is no collision
if (!collision) {
// Emit right click event
emitter.emit("rightClick", { mousePos, worldPos });
}
e.preventDefault();
});
// Get right click move position confirmation
emitter.on("rightClickPlayerMoveConfirmed", async (user) => {
myPlayer.x = user.x - 36;
myPlayer.y = user.y - 64;
// Canvas loses focus after right click, so we need to focus it again
canvas.focus();
});
// Override zoom and ctrl+scroll
canvas.addEventListener("wheel", (e: WheelEvent) => {
if (e.ctrlKey) {
e.preventDefault();
const zoomSpeed = 0.1;
if (e.deltaY < 0) {
// Zoom in
zoomFactor += zoomSpeed;
} else {
// Zoom out
zoomFactor -= zoomSpeed;
}
zoomFactor = Math.min(Math.max(zoomFactor, 0.1), 5);
}
});
}