-
Notifications
You must be signed in to change notification settings - Fork 1
/
engine.js
484 lines (397 loc) · 14.3 KB
/
engine.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
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
class InputManager {
constructor() {
this.keys = {}; // Store the state of each key (pressed or not)
this.setupKeyboardListeners();
}
setupKeyboardListeners() {
// Add event listeners for keydown and keyup events
document.addEventListener("keydown", this.handleKeyDown.bind(this));
document.addEventListener("keyup", this.handleKeyUp.bind(this));
}
handleKeyDown(event) {
// Update the key state when a key is pressed
this.keys[event.key] = true;
}
handleKeyUp(event) {
// Update the key state when a key is released
this.keys[event.key] = false;
}
isKeyPressed(key) {
// Check if a specific key is currently pressed
return this.keys[key] || false;
}
}
class Sprite {
constructor(xPos, yPos, xSize, ySize, physicsEnabled, color, mass, animAvailable, imgID) {
this.x = xPos; // X-coordinate of the sprite
this.y = yPos; // Y-coordinate of the sprite
this.width = xSize; // Width of the sprite
this.height = ySize; // Height of the sprite
this.physicsEnabled = physicsEnabled; // Whether physics apply (e.g., gravity)
this.color = color; // Color of the sprite
this.mass = mass; // Mass of the sprite
this.imgID = imgID; // Image ID of the sprite
this.flipHorizontally = false; // Flag for horizontal flipping
this.flipVertically = false; // Flag for vertical flipping
this.Gravity = 1;
this.CanvasHeight = 600;
this.xv = 0;
this.yv = 0;
this.scrollx = 0;
this.scrolly = 0;
this.falseX = 400;
this.jumping = false;
this.inputManager = new InputManager();
}
movementDefault(){
if (this.inputManager.isKeyPressed("i")) {
this.y -= 10
}
if (this.inputManager.isKeyPressed("j")) {
this.x -= 3;
}
if (this.inputManager.isKeyPressed("l")) {
this.x += 3;
}
}
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
SideScroller(userground){
this.setupSideScroll();
this.xv = 0;
this.yv = 0;
let maxSpeed = 0.75; // Set your desired maximum speed
if (this.inputManager.isKeyPressed("a")) {
this.xv += -0.75;
} else if (this.inputManager.isKeyPressed("d")) {
this.xv += 0.75;
} else {
this.xv = 0;
}
// Limit the speed
if (this.xv > maxSpeed) {
this.xv = maxSpeed;
} else if (this.xv < -maxSpeed) {
this.xv = -maxSpeed;
}
if (this.inputManager.isKeyPressed("w") && !this.jumping) {
this.yv -= 50;
this.update();
this.sleep(5000);
this.jumping = true
} else {
this.yv = 0;
}
this.x = this.xv;
this.getsidescrollpos();
let cameraDelay = 1; // Adjust this value to your liking
this.scrollx = this.scrollx + cameraDelay * (this.x - this.scrollx);
this.OBJtomove(userground);
}
FreeCamEXPERIMENTAL(userground){
this.setupSideScroll();
this.xv = 0;
this.yv = 0;
let maxSpeed = 0.75; // Set your desired maximum speed
if (this.inputManager.isKeyPressed("a")) {
this.xv -= 20;
} else if (this.inputManager.isKeyPressed("d")) {
this.xv += 20;
} else {
this.xv = 0;
}
// Limit the speed
if (this.xv > maxSpeed) {
this.xv = maxSpeed;
} else if (this.xv < -maxSpeed) {
this.xv = -maxSpeed;
}
if (this.inputManager.isKeyPressed("w") && !this.jumping) {
this.yv -= 10;
this.update();
} else if (this.inputManager.isKeyPressed("s")) {
this.yv += 10;
} else {
this.yv = 0;
}
this.x = this.xv;
this.y = this.yv;
this.getsidescrollpos();
let cameraDelay = 1; // Adjust this value to your liking
this.scrollx = this.scrollx + cameraDelay * (this.x - this.scrollx);
this.scrolly = this.scrolly + cameraDelay * (this.y - this.scrolly);
this.OBJtomove(userground);
}
setupSideScroll(){
this.scrollx = 0;
this.scrolly = 0;
this.x = 0;
this.y += this.yv;
this.yv = 0;
this.xv = 0;
}
getsidescrollpos(){
this.x = this.x - this.scrollx
this.y = this.y - this.scrolly
}
OBJtomove(userground, parallaxEnabled, distance){
if (parallaxEnabled){
userground.x = userground.x - (this.scrollx * distance);
userground.y = userground.y - (this.scrolly);
} else{
userground.x = userground.x - this.scrollx
userground.y = userground.y - this.scrolly
}
}
draw(ctx) {
// Save the current state of the canvas
ctx.save();
// Translate the canvas only in the X direction
ctx.translate(this.CanvasWidth / 2 - this.x, 0);
if (this.imgID) {
const img = new Image();
img.src = this.imgID;
// Adjust rendering based on flip flags
if (this.flipHorizontally) {
ctx.save();
ctx.scale(-1, 1); // Flip horizontally
ctx.drawImage(img, -this.x - this.width, this.y, this.width, this.height);
ctx.restore();
} else if (this.flipVertically) {
ctx.save();
ctx.scale(1, -1); // Flip vertically
ctx.drawImage(img, this.x, -this.y - this.height, this.width, this.height);
ctx.restore();
} else {
ctx.drawImage(img, this.x, this.y, this.width, this.height);
}
} else {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
// Restore the canvas to its original state
ctx.restore();
}
update() {
if (this.physicsEnabled) {
if (this.jumping) {
this.yv += this.Gravity; // Gravity pulls down
this.y += this.yv; // Velocity changes position
// If we've hit the ground, stop jumping
if (this.y >= this.CanvasHeight - this.height) {
this.y = this.CanvasHeight - this.height;
this.yv = 0;
this.jumping = false;
}
} else{
this.y += this.Gravity; // Velocity changes position
}
}
}
checkTouching(otherSprite) {
return (
this.x < otherSprite.x + otherSprite.width &&
this.x + this.width > otherSprite.x &&
this.y < otherSprite.y + otherSprite.height &&
this.y + this.height > otherSprite.y
);
}
collisionHandling(collisionSprite) {
if (this.checkTouching(collisionSprite)) {
this.jumping = false;
// Calculate total mass for pushing behavior
const totalMass = this.mass + collisionSprite.mass;
// Calculate relative mass ratio
const massRatio = this.mass / collisionSprite.mass;
// Adjust positions based on mass ratio
const overlapX = Math.min(
Math.abs(this.x - collisionSprite.x - collisionSprite.width),
Math.abs(this.x + this.width - collisionSprite.x)
);
const overlapY = Math.min(
Math.abs(this.y - collisionSprite.y - collisionSprite.height),
Math.abs(this.y + this.height - collisionSprite.y)
);
if (overlapX < overlapY) {
if (this.x < collisionSprite.x) {
this.x = collisionSprite.x - this.width;
collisionSprite.x += overlapX * massRatio;
} else {
this.x = collisionSprite.x + collisionSprite.width;
collisionSprite.x -= overlapX * massRatio;
}
} else {
if (this.y < collisionSprite.y) {
this.y = collisionSprite.y - this.height;
collisionSprite.y += overlapY * massRatio;
} else {
this.y = collisionSprite.y + collisionSprite.height;
collisionSprite.y -= overlapY * massRatio;
}
}
}
}
}
class AudioManager {
constructor() {
this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
this.sounds = new Map(); // Store loaded audio buffers
}
async loadSound(url) {
try {
const response = await fetch(url);
const arrayBuffer = await response.arrayBuffer();
const audioBuffer = await this.audioContext.decodeAudioData(arrayBuffer);
this.sounds.set(url, audioBuffer);
return audioBuffer;
} catch (error) {
console.error(`Error loading sound from ${url}: ${error.message}`);
return null;
}
}
playSound(url, volume = 1.0) {
const buffer = this.sounds.get(url);
if (buffer) {
const source = this.audioContext.createBufferSource();
source.buffer = buffer;
const gainNode = this.audioContext.createGain();
gainNode.gain.value = volume;
source.connect(gainNode);
gainNode.connect(this.audioContext.destination);
source.start();
} else {
console.warn(`Sound not loaded: ${url}`);
}
}
}
class ParticleManager {
constructor() {
this.particles = [];
}
createParticle(x, y, velocityX, velocityY, lifetime) {
const particle = {
x,
y,
velocityX,
velocityY,
lifetime,
};
this.particles.push(particle);
}
createRandomParticle(x, y, lifetime) {
const velocityX = Math.random() * 2 - 1; // Random X velocity between -1 and 1
const velocityY = Math.random() * 2 - 1; // Random Y velocity between -1 and 1
this.createParticle(x, y, velocityX, velocityY, lifetime);
}
updateParticles() {
for (let i = this.particles.length - 1; i >= 0; i--) {
const particle = this.particles[i];
particle.x += particle.velocityX;
particle.y += particle.velocityY;
particle.lifetime--;
if (particle.lifetime <= 0) {
this.particles.splice(i, 1); // Remove expired particles
}
}
}
renderParticles(context, color) {
context.fillStyle = color; // Particle color
for (const particle of this.particles) {
context.fillRect(particle.x, particle.y, 5, 5); // Draw a small square for each particle
}
}
}
class Animation {
constructor(imageArray) {
this.frames = imageArray; // Array of image URLs or Image objects
this.currentFrame = 0; // Index of the current frame
this.frameInterval = 100; // Time (in milliseconds) between frames
this.isPlaying = false; // Whether the animation is currently playing
this.playElgibility = false;
}
playOnSprite(targetSprite) {
this.playElgibility = true;
if(this.playElgibility == true){
if (!this.isPlaying) {
this.isPlaying = true;
const animate = () => {
if(this.playElgibility == true){
targetSprite.imgID = this.frames[this.currentFrame];
this.currentFrame = (this.currentFrame + 1) % this.frames.length;
setTimeout(animate, this.frameInterval);
}
};
animate();
}
}
}
stop() {
this.isPlaying = false;
this.playElgibility = false;
this.currentFrame = 0;
}
setFrame(frameIndex) {
if (frameIndex >= 0 && frameIndex < this.frames.length) {
this.currentFrame = frameIndex;
} else {
console.error('Invalid frame index.');
}
}
}
class UIManager {
constructor(canvas, ctx, x, y, width, height, color, text, font = '40pt Arial', fontColor, borderWidth, borderColor, onclick, notclicked){
this.canvas = canvas;
this.ctx = ctx;
this.onclick = onclick
this.notclicked = notclicked;
this.text = text
this.rect = {
x: x,
y: y,
fontColor: fontColor,
width: width,
height: height,
color: color,
font: font,
borderWidth: borderWidth,
borderColor: borderColor,
}
this.canvas.addEventListener('click', (evt) => {
this.MousePos = this.getMousePos(evt)
if (this.isInside(this.MousePos, this.rect)) {
this.onclick();
} else {
}
}, false);
}
getMousePos(event) {
var rect = this.canvas.getBoundingClientRect();
return {
x: event.clientX - rect.left,
y: event.clientY - rect.top,
};
}
isInside(pos, rect) {
return pos.x > rect.x && pos.x < rect.x + rect.width && pos.y < rect.y + rect.height && pos.y > rect.y
}
drawUI() {
this.ctx.beginPath();
this.ctx.rect(this.rect.x, this.rect.y, this.rect.width, this.rect.height);
this.ctx.fillStyle = this.rect.color;
this.ctx.fill();
this.ctx.lineWidth = this.rect.borderWidth;
this.ctx.strokeStyle = this.rect.borderColor;
this.ctx.stroke();
this.ctx.closePath();
this.ctx.font = this.rect.font;
this.ctx.fillStyle = this.rect.fontColor;
// Measure the width of the text
var textWidth = this.ctx.measureText(this.text).width;
// Calculate the position to center the text
var textX = this.rect.x + (this.rect.width - textWidth) / 2;
var textY = this.rect.y + (this.rect.height + parseInt(this.rect.font)) / 2;
this.ctx.fillText(this.text, textX, textY);
}
}
export{Sprite, InputManager, AudioManager, ParticleManager, Animation, UIManager}