-
Notifications
You must be signed in to change notification settings - Fork 0
/
BulletController.js
55 lines (46 loc) · 1.45 KB
/
BulletController.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
import Bullet from "./Bullet.js";
export default class BulletController {
bullets = [];
timeTillNextBulletAllowed = 0;
constructor(canvas, maxBulletsAtATime, bulletColor, soundEnabled) {
this.canvas = canvas;
this.maxBulletsAtATime = maxBulletsAtATime;
this.bulletColor = bulletColor;
this.soundEnabled = soundEnabled;
this.shootSound = new Audio("sounds/shoot.wav");
this.shootSound.volume = 0.1;
}
draw(ctx) {
this.bullets = this.bullets.filter(
(bullet) => bullet.y + bullet.width > 0 && bullet.y <= this.canvas.height
);
this.bullets.forEach((bullet) => bullet.draw(ctx));
if (this.timeTillNextBulletAllowed > 0) {
this.timeTillNextBulletAllowed--;
}
}
collideWith(sprite) {
const bulletThatHitSpriteIndex = this.bullets.findIndex((bullet) =>
bullet.collideWith(sprite)
);
if (bulletThatHitSpriteIndex >= 0) {
this.bullets.splice(bulletThatHitSpriteIndex, 1);
return true;
}
return false;
}
shoot(x, y, velocity, timeTillNextBulletAllowed = 0) {
if (
this.timeTillNextBulletAllowed <= 0 &&
this.bullets.length < this.maxBulletsAtATime
) {
const bullet = new Bullet(this.canvas, x, y, velocity, this.bulletColor);
this.bullets.push(bullet);
if (this.soundEnabled) {
this.shootSound.currentTime = 0;
this.shootSound.play();
}
this.timeTillNextBulletAllowed = timeTillNextBulletAllowed;
}
}
}