-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.ts
289 lines (255 loc) · 7.7 KB
/
main.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
import { emitter } from "@/composables/useEmit";
import type { User } from "@/types/general";
import { loadImage, isColliding } from "./utilities";
import { drawPlayer } from "./draw";
import { updateAnimationFrame } from "./animations";
import { keyDownEventListener, keyUpEventListener } from "./keyboardEvents";
import { rightClickEventListener, wheelEventListener } from "./mouseEvents";
export async function createCanvasApp(
users: User[],
myPlayerId: string,
speed: number,
canvas: HTMLCanvasElement,
canvasFrameRate: number,
spaceMap: string,
myCharacterSprite: string,
initialSetupCompleted: boolean
) {
const ctx = canvas.getContext("2d")!;
// Load images
const worldImg = await loadImage(spaceMap);
const characterImg = await loadImage(myCharacterSprite);
const characterImgMyPlayer = await 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;
});
/****************************************
* THE GAME LOOP
****************************************/
const gameLoop = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Set myPlayer
myPlayer = users.find((user) => user.id === myPlayerId)!;
if (myPlayer) {
// Center camera on my player
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];
// check if any key is pressed
if (pressedKeys.w || pressedKeys.a || pressedKeys.s || pressedKeys.d) {
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);
}
};
// Init game loop
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);
}
const getCamera = () => {
return {
cameraX: myPlayer?.x - canvas.width / (2.2 * zoomFactor),
cameraY: myPlayer.y - canvas.height / (2.2 * zoomFactor),
zoomFactor,
};
};
// LISTENERS
keyDownEventListener(canvas, pressedKeys, keyPressOrder, () => myPlayer);
keyUpEventListener(canvas, pressedKeys, keyPressOrder, () => myPlayer);
rightClickEventListener(canvas, getCamera, users, myPlayerId);
wheelEventListener(canvas, zoomFactor);
// 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();
});
}