-
Notifications
You must be signed in to change notification settings - Fork 1
/
main4.ts
400 lines (345 loc) · 10.4 KB
/
main4.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
import { emitter } from "@/composables/useEmit";
import type { User } from "@/types/general";
import type { CanvasAppOptions, Camera } from "@/types/canvasTypes";
import {
loadImage,
isColliding,
matchUserFacingToAnimationState,
} from "./utilities";
import { drawWorld, drawPlayerBanner, drawPlayer } from "./draw";
import { updateAnimationFrame } from "./animations";
import { keyDownEventListener, keyUpEventListener } from "./keyboardEvents";
import { rightClickEventListener, wheelEventListener } from "./mouseEvents";
import { isPlayerInRoom } from "./roomDetection";
async function createCanvasApp(options: CanvasAppOptions): Promise<void> {
const {
users,
myPlayerId,
speed,
canvas,
canvasFrameRate,
spaceMap,
myCharacterSprite,
initialSetupCompleted,
} = options;
const ctx = canvas.getContext("2d")!;
const [worldImg, characterImg, characterImgMyPlayer] = await Promise.all([
loadImage(spaceMap),
loadImage(myCharacterSprite),
loadImage(myCharacterSprite),
]);
let camera: Camera = {
cameraX: 200,
cameraY: 200,
zoomFactor: 1,
};
let myPlayer: User = {
id: "",
userName: "",
x: 0,
y: 0,
characterSprite: "",
facingTo: "",
userStatus: "",
};
// Tracks the order of movement keys (W, A, S, D) being pressed. It helps determine the character's movement direction when multiple keys are pressed, prioritizing the last valid key pressed.
let keyPressOrder: string[] = [];
const pressedKeys: Record<string, boolean> = {
w: false,
a: false,
s: false,
d: false,
};
// Animation related
let animationState = "walk-down";
let animationFrame = 0;
let animationTick = 0;
// FPS counter
let lastTime = performance.now();
let fps = 0;
// FPS limiting
let lastUpdateTime = 0;
const frameDuration = 1000 / canvasFrameRate;
let mouseX = 0;
let mouseY = 0;
const roomLayer: { data: number[] } = {
data: [],
};
// Track mouse position (used for checking if mouse is hovering over a player)
canvas.addEventListener("mousemove", (e: MouseEvent) => {
mouseX = e.clientX;
mouseY = e.clientY;
});
function gameLoop(timestamp: number) {
// Calculate the elapsed time since the last update
let elapsedTime = timestamp - lastUpdateTime;
if (elapsedTime >= frameDuration) {
// Clear the canvas before drawing to prevent ghosting effect
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Anti-aliasing in browsers smooths images, which can blur pixel art or low-res graphics
ctx.imageSmoothingEnabled = false;
myPlayer = users.find((user) => user.id === myPlayerId)!;
if (myPlayer) {
// Center camera on my player
camera.cameraX = myPlayer.x - canvas.width / (2.2 * camera.zoomFactor);
camera.cameraY = myPlayer.y - canvas.height / (2.2 * camera.zoomFactor);
drawWorld(ctx, worldImg, camera);
handlePlayerMovement();
drawOtherPlayers();
drawMyPlayer();
drawAllPlayerNames();
updateAnimation();
drawFPS();
const playerTilePosition = getPlayerTilePosition();
if (
playerTilePosition.x >= 13 &&
playerTilePosition.y <= 20 &&
playerTilePosition.y <= 6 &&
playerTilePosition.y >= 2
) {
emitter.emit("playerInRoom", true);
} else {
emitter.emit("playerInRoom", false);
}
/* const inRoom = isPlayerInRoom(roomLayer, playerTilePosition, mapWidth); */
}
lastUpdateTime = timestamp;
}
requestAnimationFrame(gameLoop);
}
// HELPER FUNCTIONS
// 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
function handlePlayerMovement() {
if (keyPressOrder.length > 0) {
let newPlayerX = myPlayer.x;
let newPlayerY = myPlayer.y;
const lastValidKey = keyPressOrder[keyPressOrder.length - 1];
// Check if any key is pressed to prevent continuous movement
if (pressedKeys.w || pressedKeys.a || pressedKeys.s || pressedKeys.d) {
switch (lastValidKey) {
case "w":
newPlayerY -= speed;
animationState = "walk-up";
myPlayer.facingTo = "up";
break;
case "a":
newPlayerX -= speed;
animationState = "walk-left";
myPlayer.facingTo = "left";
break;
case "s":
newPlayerY += speed;
animationState = "walk-down";
myPlayer.facingTo = "down";
break;
case "d":
newPlayerX += speed;
animationState = "walk-right";
myPlayer.facingTo = "right";
break;
}
}
// Check for collisions with other players
const playerWidth = 48 * camera.zoomFactor;
const playerHeight = 64 * camera.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;
}
}
}
function drawOtherPlayers() {
users.forEach((user) => {
if (user.id !== myPlayerId) {
const playerRect = {
x: (user.x - camera.cameraX - 8) * camera.zoomFactor,
y: (user.y - camera.cameraY - 8) * camera.zoomFactor,
width: 96 * camera.zoomFactor,
height: 96 * camera.zoomFactor,
};
// Check if mouse is over the player
const isMouseOver = isColliding(
{ x: mouseX, y: mouseY, width: 1, height: 1 },
playerRect
);
drawPlayer(
ctx,
characterImg,
matchUserFacingToAnimationState(user.facingTo),
1,
user,
camera.cameraX,
camera.cameraY,
camera.zoomFactor,
user.userStatus,
isMouseOver
);
}
});
}
function drawMyPlayer() {
const playerRect = {
x: (myPlayer.x - camera.cameraX - 8) * camera.zoomFactor,
y: (myPlayer.y - camera.cameraY - 8) * camera.zoomFactor,
width: 96 * camera.zoomFactor,
height: 96 * camera.zoomFactor,
};
const isMouseOver = isColliding(
{ x: mouseX, y: mouseY, width: 1, height: 1 },
playerRect
);
drawPlayer(
ctx,
characterImgMyPlayer,
animationState,
animationFrame,
myPlayer,
camera.cameraX,
camera.cameraY,
camera.zoomFactor,
myPlayer.userStatus,
isMouseOver
);
}
function drawAllPlayerNames() {
// Draw other players' names
users.forEach((user) => {
if (user.id !== myPlayerId) {
drawPlayerBanner(
ctx,
user,
camera.cameraX,
camera.cameraY,
camera.zoomFactor
);
}
});
// Draw your player's name
drawPlayerBanner(
ctx,
myPlayer,
camera.cameraX,
camera.cameraY,
camera.zoomFactor
);
}
function getPlayerTilePosition(): {
x: number;
y: number;
} {
const tileWidth = 32; // Set the width of a tile in your map
const tileHeight = 32; // Set the height of a tile in your map
return {
x: Math.floor(myPlayer.x / tileWidth),
y: Math.floor(myPlayer.y / tileHeight),
};
}
function updateAnimation() {
[animationFrame, animationTick] = updateAnimationFrame(
pressedKeys,
animationState,
animationFrame,
animationTick
);
}
function drawFPS() {
// Calculate FPS
const currentTime = performance.now();
const deltaTime = currentTime - lastTime;
lastTime = currentTime;
// Draw FPS
fps = Math.round(1000 / deltaTime);
ctx.fillStyle = "black";
ctx.font = "bold 16px Poppins";
ctx.fillText(`FPS: ${fps}`, 10, 20);
}
function initGameLoop() {
if (
users.length > 0 &&
myPlayerId !== "" &&
speed !== 0 &&
spaceMap !== "" &&
initialSetupCompleted
) {
requestAnimationFrame(gameLoop);
} else {
const checkConditionsBeforeLoop = setInterval(() => {
if (
users.length > 0 &&
myPlayerId !== "" &&
speed !== 0 &&
spaceMap !== "" &&
initialSetupCompleted
) {
requestAnimationFrame(gameLoop);
clearInterval(checkConditionsBeforeLoop);
// Emit event to notify Space.vue that the canvas is loaded
emitter.emit("canvasLoaded");
}
}, 0);
}
}
function getCamera(): Camera {
return {
cameraX: myPlayer?.x - canvas.width / (2.2 * camera.zoomFactor),
cameraY: myPlayer.y - canvas.height / (2.2 * camera.zoomFactor),
zoomFactor: camera.zoomFactor,
};
}
keyDownEventListener(canvas, pressedKeys, keyPressOrder, () => myPlayer);
keyUpEventListener(canvas, pressedKeys, keyPressOrder, () => myPlayer);
rightClickEventListener(canvas, getCamera, users, myPlayerId);
wheelEventListener(canvas, camera);
// Get right click move position confirmation from Space.vue and move the player
emitter.on("rightClickPlayerMoveConfirmed", async (user) => {
myPlayer.x = user.x;
myPlayer.y = user.y;
// Canvas loses focus after right click, so we need to focus it again
canvas.focus();
});
// Get joystick move event from Joystick.vue and move the player
emitter.on("joystickMove", async (direction: string) => {
if (direction === "up") {
pressedKeys.w = true;
keyPressOrder.push("w");
} else if (direction === "left") {
pressedKeys.a = true;
keyPressOrder.push("a");
} else if (direction === "down") {
pressedKeys.s = true;
keyPressOrder.push("s");
} else if (direction === "right") {
pressedKeys.d = true;
keyPressOrder.push("d");
}
if (direction === "none") {
pressedKeys.w = false;
pressedKeys.a = false;
pressedKeys.s = false;
pressedKeys.d = false;
keyPressOrder = [];
emitter.emit("playerMove", myPlayer);
}
});
// Start the game loop
initGameLoop();
}
export { createCanvasApp };