-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
666 lines (605 loc) · 20.9 KB
/
index.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
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
/*ASAteroids is a modified version of Base Defense Game from
Chris' Courses, which can be found here:
https://chriscourses.com/courses/javascript-games/videos/project-setup
TODOs:
1) Add upgrade items / upgrade particle physics
(bombshot need to fix score for each enemy killed)
2) Add leaderboard to track high scores
3) Add boss fights*/
const canvas = document.querySelector('canvas');
//using "c" instead of "context" because this will be repeated a lot
const c = canvas.getContext('2d');
//enemy icons directory and array
const enemyDir = "./enemies/";
const enemyFiles = [
"icon-ada.svg",
"icon-atom.svg",
"icon-bnb.svg",
"icon-btc.svg",
"icon-doge.svg",
"icon-eth.svg",
"icon-ltc.svg",
"icon-shib.svg",
"icon-sol.svg",
"icon-trx.svg",
"icon-usdt.svg",
"icon-xmr.svg"
];
const enemySprite = enemyFiles.map(file => enemyDir + file);
//upgrade icons directory and array
const upgradeDir = "./upgrades/";
const upgradeFiles = [
"icon-afd.svg",
"icon-algo.svg",
"icon-dc.svg",
"icon-grad.svg",
"icon-ogs.svg",
"icon-puddin.svg",
"icon-trts.svg"
];
const upgradeSprite = upgradeFiles.map(file => upgradeDir + file);
const scoreEl = document.querySelector('#scoreEl');
const modal = document.querySelector('#modal');
const modalScore = document.querySelector('#modalScore');
const button = document.querySelector('#button');
const startButton = document.querySelector('#startButton');
const startModal = document.querySelector('#startModal');
canvas.width = innerWidth;
canvas.height = innerHeight;
class Player {
constructor(x, y, radius, playerImage) {
this.x = x
this.y = y
this.radius = radius
this.image = document.querySelector('#playerImage')
}
draw() {
c.drawImage(this.image, this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2)
}
};
class Projectile {
constructor(x, y, radius, color, velocity) {
this.x = x
this.y = y
this.radius = radius
this.color = color
this.velocity = velocity
}
draw() {
c.beginPath()
c.arc(this.x, this.y, this.radius,
0, Math.PI * 2, false)
c.fillStyle = this.color
c.fill()
}
update() {
this.draw()
this.x = this.x + this.velocity.x
this.y = this.y + this.velocity.y
}
};
class Enemy {
constructor(x, y, radius, color, velocity, enemyImage) {
this.x = x
this.y = y
this.radius = radius
this.color = color
this.velocity = velocity
this.enemyImage = enemyImage;
}
draw() {
c.drawImage(
this.enemyImage,
this.x - this.radius,
this.y - this.radius,
this.radius * 2,
this.radius * 2
)
}
update() {
this.draw()
this.x = this.x + this.velocity.x
this.y = this.y + this.velocity.y
}
};
class Upgrade {
constructor(x, y, radius, color, velocity, upgradeImage) {
this.x = x
this.y = y
this.radius = radius
this.color = color
this.velocity = velocity
this.upgradeImage = upgradeImage;
}
draw() {
c.drawImage(
this.upgradeImage,
this.x - this.radius,
this.y - this.radius,
this.radius * 2,
this.radius * 2
)
}
update() {
this.draw()
this.x = this.x + this.velocity.x
this.y = this.y + this.velocity.y
}
};
const friction = 0.98; //closer to zero moves particles more slowly
class Particle {
constructor(x, y, radius, color, velocity) {
this.x = x
this.y = y
this.radius = radius
this.color = color
this.velocity = velocity
this.alpha = 1
}
draw() {
c.save()
c.globalAlpha = this.alpha
c.beginPath()
c.arc(this.x, this.y, this.radius,
0, Math.PI * 2, false)
c.fillStyle = this.color
c.fill()
c.restore()
}
update() {
this.draw()
this.velocity.x *= friction
this.velocity.y *= friction
this.x = this.x + this.velocity.x
this.y = this.y + this.velocity.y
this.alpha -= 0.01
}
};
const x = canvas.width / 2;
const y = canvas.height / 2;
let player = new Player(x, y, 15);
let projectiles = [];
let enemies = [];
let particles = [];
let upgrades = [];
let animationId;
let intervalId;
let upgradeInterval
let score = 0;
let scatterShotActive = false;
let scatterShotTimeoutId = null;
let shieldActive = false;
let shieldTimeoutId = null;
let bombShotActive = false;
let bombShotTimeoutId = null;
let bombFired = false;
let rapidFireActive = false;
let rapidFireTimeoutId = null;
let rapidFireIntervalId = null;
function startScatterShot() {
scatterShotActive = true;
clearTimeout(scatterShotTimeoutId);
scatterShotTimeoutId = setTimeout(() => {
scatterShotActive = false;
}, 10000); // set to 10 seconds
}
function startBombShot() {
bombShotActive = true;
clearTimeout(bombShotTimeoutId);
bombShotTimeoutId = setTimeout(() => {
bombShotActive = false;
}, 10000); // set to 10 seconds
}
function startRapidFire() {
rapidFireActive = true;
clearTimeout(rapidFireTimeoutId);
rapidFireTimeoutId = setTimeout(() => {
rapidFireActive = false;
clearInterval(rapidFireIntervalId);
}, 10000); // set to 10 seconds
}
function startShield() {
shieldActive = true;
shieldTimeoutId = setTimeout(() => {
shieldActive = false;
}, 15000) // set to 10 seconds
const startTime = performance.now();
function shieldAnimate() {
const elapsedTime = performance.now() - startTime;
c.beginPath();
c.arc(player.x, player.y, player.radius + 50, 0, Math.PI * 2, false);
c.strokeStyle = 'purple';
c.lineWidth = 7;
c.stroke();
if (elapsedTime < 15000) {
requestAnimationFrame(shieldAnimate);
}
}
shieldAnimate();
}
function init() {
player = new Player(x, y, 15)
projectiles = []
enemies = []
particles = []
upgrades = []
animationId
score = 0
scoreEl.innerHTML = 0
scatterShotActive = false
scatterShotTimeoutId = null
shieldActive = false
shieldTimeoutId = null
bombShotActive = false
bombShotTimeoutId = null
bombFired = false
rapidFireActive = false
rapidFireTimeoutId = null
rapidFireIntervalId = null
checkMusicToggle()
};
function spawnEnemies() {
intervalId = setInterval(() => {
console.log('intervalId');
const radius = Math.random() * (30 - 4) + 4
let x
let y
if (Math.random() < 0.5) {
x = Math.random() < 0.5 ? 0 - radius : canvas.width + radius
y = Math.random() * canvas.height
} else {
x = Math.random() * canvas.width
y = Math.random() < 0.5 ? 0 - radius : canvas.height + radius
}
const color = `hsl(${Math.random() * 360}, 50%, 50%)`
const angle = Math.atan2(
canvas.height / 2 - y,
canvas.width / 2 - x)
const velocity = {
x: Math.cos(angle),
y: Math.sin(angle)
}
const enemyImage = new Image();
enemyImage.src = enemySprite[Math.floor(Math.random() * enemySprite.length)];
enemies.push(new Enemy(x, y, radius, color, velocity, enemyImage))
}, 1000)
}
function spawnUpgrades() {
upgradeInterval = setInterval(() => {
const radius = 20
let x
let y
if (Math.random() < 0.5) {
x = Math.random() < 0.5 ? 0 - radius : canvas.width + radius
y = Math.random() * canvas.height
} else {
x = Math.random() * canvas.width
y = Math.random() < 0.5 ? 0 - radius : canvas.height + radius
}
const color = 'purple'
const angle = Math.atan2(
canvas.height / 2 - y,
canvas.width / 2 - x)
const velocity = {
x: Math.cos(angle),
y: Math.sin(angle)
}
const upgradeImage = new Image();
upgradeImage.src = upgradeSprite[Math.floor(Math.random() * upgradeSprite.length)];
upgrades.push(new Upgrade(x, y, radius, color, velocity, upgradeImage))
console.log('New upgrade deployed!', upgradeImage)
}, 30000)
}
function checkMusicToggle() {
const backgroundMusic = document.querySelector('#backgroundMusic');
const musicToggle = document.querySelector('.switch input[type="checkbox"]');
if (musicToggle.checked) {
backgroundMusic.play();
} else {
backgroundMusic.pause();
}
};
//helper function communicates score using postmessage
function sendScoreToParent(score) {
window.parent.postMessage({ type: 'PLAYER_SCORE', score: score }, '*');
console.log("postmessage:", score);
};
function animate() {
checkMusicToggle()
animationId = requestAnimationFrame(animate)
c.fillStyle = 'rgb(0, 0, 0, 0.1)'
c.fillRect(0, 0, canvas.width, canvas.height)
player.draw();
//all loops start at end of the array and iterate backwards
//this makes it easier to remove items from the array
//this loop updates/animates particles, and removes them
//from the particles array when the alpha attr is <= 0
for (let index = particles.length - 1; index >= 0; index--) {
const particle = particles[index]
if (particle.alpha <= 0) {
particles.splice(index, 1)
} else {
particle.update();
}
};
//animate projectiles and remove from array at edge of screen
for (let index = projectiles.length - 1; index >= 0; index--) {
const projectile = projectiles[index]
projectile.update()
//remove projectiles from left/right/top/bottom edges of screen
if (projectile.x + projectile.radius < 0 ||
projectile.x - projectile.radius > canvas.width ||
projectile.y + projectile.radius < 0 ||
projectile.y - projectile.radius > canvas.height) {
projectiles.splice(index, 1)
bombFired = false;
}
};
//Upgrade item / player tracking / hit detection
for (let index = upgrades.length -1; index >= 0; index--) {
const upgrade = upgrades[index]
upgrade.update()
//track distance between player and upgrade item
const dist = Math.hypot(player.x - upgrade.x, player.y - upgrade.y)
//upgrade item/ player hit detection
if (dist - upgrade.radius - player.radius < 1) {
let upgradeImage = upgrade.upgradeImage
let acquiredUpgrade = upgradeImage.src.match(/\/([^/]+)\.[^.]+$/)[1];
//gsap animate shrink upgrade when it touches player
gsap.to(upgrade, {
//actual shrink physics:
radius: upgrade.radius - 10,
onComplete: () => {
//remove upgrade from upgrades array after shrinking
upgrades.splice(index, 1)
//based on upgrade item, set upgrade type:
if (acquiredUpgrade == "icon-afd") {
console.log('Scatter Shot Acquired!', upgrade.upgradeImage);
startScatterShot();
} else if (acquiredUpgrade == "icon-algo") {
console.log('Shield Acquired!', upgrade.upgradeImage);
startShield();
} else if (acquiredUpgrade == "icon-dc") {
console.log('Rapid Fire Acquired!', upgrade.upgradeImage);
startRapidFire();
} else if (acquiredUpgrade == "icon-grad") {
console.log('Bombs Acquired!', upgrade.upgradeImage);
startBombShot();
} else if (acquiredUpgrade == "icon-ogs") {
console.log('Gnomes Acquired!', upgrade.upgradeImage);
startRapidFire();
} else if (acquiredUpgrade == "icon-puddin") {
console.log('Rear Cannons Acquired!', upgrade.upgradeImage);
startScatterShot();
} else if (acquiredUpgrade == "icon-trts") {
console.log('Treats acquired:', upgrade.upgradeImage);
startBombShot();
}
}
})
}
}
for (let index = enemies.length - 1; index >= 0; index--) {
const enemy = enemies[index]
enemy.update()
//dist tracks distance between enemies and player
const dist = Math.hypot(player.x - enemy.x, player.y - enemy.y)
const borderDist = dist - player.radius - 55;
if (!shieldActive) {
//if distance between enemy and player is less than 1px, end game
if (dist - enemy.radius - player.radius < 1) {
cancelAnimationFrame(animationId)
clearInterval(intervalId)
clearInterval(upgradeInterval)
backgroundMusic.pause();
backgroundMusic.currentTime = 0;
modal.style.display = 'block'
gsap.fromTo('#modal', {scale: 0.8, opacity: 0}, {
scale: 1, opacity: 1,
ease: 'expo'
})
modalScore.innerHTML = score
sendScoreToParent(score);
}
} else {
if (borderDist - enemy.radius < 1) {
//enemy particle explosion on touching shield
for (let i = 0; i < enemy.radius * 2; i++) {
particles.push(
new Particle(
enemy.x,
enemy.y,
Math.random() * 2,
enemy.color,
{
x: (Math.random() - 0.5) * (Math.random() * 8),
y: (Math.random() - 0.5) * (Math.random() * 8)
}
)
)
}
if (enemy.radius - 10 > 5) {
score += 100
scoreEl.innerHTML = score
gsap.to(enemy, {
radius: enemy.radius - enemy.radius
})
} else {
//remove enemy if they are destroyed
score += 150
scoreEl.innerHTML = score
enemies.splice(index, 1)
}
}
}
for (let projectilesIndex = projectiles.length - 1; projectilesIndex >= 0; projectilesIndex--) {
const projectile = projectiles[projectilesIndex]
//tracking
const dist = Math.hypot(projectile.x - enemy.x, projectile.y - enemy.y)
//projectile enemy collision
if (dist - enemy.radius - projectile.radius < 1) {
//create enemy particle explosion
for (let i = 0; i < enemy.radius * 2; i++) {
particles.push(
new Particle(
projectile.x,
projectile.y,
Math.random() * 2,
enemy.color,
{
x: (Math.random() - 0.5) * (Math.random() * 8),
y: (Math.random() - 0.5) * (Math.random() * 8)
}
)
)
}
//where we shrink our enemy
if (enemy.radius - 10 > 5) {
score += 100
scoreEl.innerHTML = score
gsap.to(enemy, {
radius: enemy.radius - 10
})
projectiles.splice(projectilesIndex, 1)
bombFired = false
} else {
//remove enemy if they are destroyed
score += 150
scoreEl.innerHTML = score
enemies.splice(index, 1)
projectiles.splice(projectilesIndex, 1)
bombFired = false
}
}
}
}
};
addEventListener('click', (event) => {
/*if rapid fire is active,
ignore click event listener
(rapid fire handled by
mousedown/up event listeners)*/
if(rapidFireActive) {
return;
}
const angle = Math.atan2(
event.clientY - canvas.height / 2,
event.clientX - canvas.width / 2)
//bullet speed
const velocity = {
x: Math.cos(angle) * 5,
y: Math.sin(angle) * 5
}
if (scatterShotActive)
{
// if scatterShot is active, create multiple bullets
for (let i = 0; i <= 5; i++) {
const spreadAngle = (Math.PI / 25) * (i - 2);
const spreadVelocity = {
x: Math.cos(angle + spreadAngle) * 5,
y: Math.sin(angle + spreadAngle) * 5
}
projectiles.push(new Projectile(
canvas.width/2, canvas.height / 2, 5, 'red', spreadVelocity, true
));
}
}
else if (bombShotActive && !bombFired)
{
projectiles.push(new Projectile(
canvas.width / 2, canvas.height / 2, 25, 'blue', velocity
))
//set bombFired to true to indicate that bomb has been fired
bombFired = true;
//set timeout to reset to false after (if needed, will go after this code)
}
else if (bombShotActive && bombFired)
{
const blueIndex = projectiles.findIndex(p => p.color === "blue")
const projectile = projectiles[blueIndex]
projectile.update();
projectiles.splice(blueIndex, 1);
//draw shockwave when bomb explodes
c.globalAlpha = 0.5; // set opacity to 50%
c.fillStyle = "blue"; // set shockwave background color
c.beginPath();
c.arc(projectile.x, projectile.y, 250, 0, 2 * Math.PI);
c.fill();
c.globalAlpha = 1; // reset opacity to 100%
//remove/kill enemies inside shockwave radius
enemies = enemies.filter((enemy) => {
const distance = Math.hypot(enemy.x - projectile.x, enemy.y - projectile.y);
return distance > 250 ? true : false; // keep enemies outside the blue circle
});
//reset bombFired to false to shoot new bombShots (before upgrade wears out)
score += 150
scoreEl.innerHTML = score
bombFired = false;
}
else
{
//if upgrade is not active, shoot regular projectiles:
projectiles.push(new Projectile(
canvas.width / 2, canvas.height / 2, 5, 'white', velocity
))
}
});
const rapidVelocity = { x: 0, y: 0 };
//function to update velocity based on mouse current position
function updateVelocity(event) {
const angle = Math.atan2(
event.clientY - canvas.height / 2,
event.clientX - canvas.width / 2);
rapidVelocity.x = Math.cos(angle) * 5;
rapidVelocity.y = Math.sin(angle) * 5;
}
//mousedown event listener turns on rapid fire if upgrade is active:
addEventListener('mousedown', (event) => {
if (rapidFireActive)
{
//call updateVelocity immediately to set initial velocity
updateVelocity(event);
//mousemove event listener updates velocity as the mouse moves
canvas.addEventListener('mousemove', updateVelocity);
rapidFireIntervalId = setInterval(() => {
projectiles.push(new Projectile(
canvas.width / 2, canvas.height / 2, 5, 'red', rapidVelocity
));
}, 100); // fire a projectile every 100 milliseconds
}
});
//mouseup event listener turns off rapid fire
addEventListener('mouseup', (event) => {
clearInterval(rapidFireIntervalId);
canvas.removeEventListener('mousemove', updateVelocity);
});
button.addEventListener('click', () => {
init()
animate()
spawnEnemies()
spawnUpgrades()
gsap.to('#modal', {
opacity: 0,
scale: 0.8,
duration: 0.2,
ease: 'expo.in',
onComplete: () => {
modal.style.display = 'none'
}
})
});
startButton.addEventListener('click', () => {
init()
animate()
spawnEnemies()
spawnUpgrades()
gsap.to('#startModal', {
opacity: 0,
scale: 0.8,
duration: 0.2,
ease: 'expo.in', //google gsap visualizer
onComplete: () => {
startModal.style.display = 'none'
}
})
});