-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCactiController.js
76 lines (62 loc) · 1.75 KB
/
CactiController.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
import Cactus from "./Cactus.js";
export default class CactiController {
CACTUS_INTERVAL_MIN = 500;
CACTUS_INTERVAL_MAX = 2000;
nextCactusInterval = null;
cacti = [];
constructor(ctx, cactiImages, scaleRatio, speed) {
this.ctx = ctx;
this.canvas = ctx.canvas;
this.cactiImages = cactiImages;
this.scaleRatio = scaleRatio;
this.speed = speed;
this.setNextCactusTime();
}
setNextCactusTime() {
const num = this.getRandomNumber(
this.CACTUS_INTERVAL_MIN,
this.CACTUS_INTERVAL_MAX
);
this.nextCactusInterval = num;
}
getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
createCactus() {
const idx = this.getRandomNumber(0, this.cactiImages.length - 1);
const cactusImage = this.cactiImages[idx];
const x = this.canvas.width * 1.5;
const y = this.canvas.height - cactusImage.height;
const cactus = new Cactus(
this.ctx,
x,
y,
cactusImage.width,
cactusImage.height,
cactusImage.image
);
this.cacti.push(cactus);
}
update(gameSpeed, frameTimeDelta) {
if (this.nextCactusInterval <= 0) {
// create cactus
this.createCactus();
this.setNextCactusTime();
}
this.nextCactusInterval -= frameTimeDelta;
this.cacti.forEach((cactus) => {
cactus.update(this.speed, gameSpeed, frameTimeDelta, this.scaleRatio);
});
// decrease the number of created cactus when it disappered from the screen
this.cacti = this.cacti.filter((cactus) => cactus.x > -cactus.width);
}
draw() {
this.cacti.forEach((cactus) => cactus.draw());
}
collideWith(sprite) {
return this.cacti.some((cactus) => cactus.collideWith(sprite));
}
reset() {
this.cacti = [];
}
}