forked from vikram-kangotra/Dino
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcactus.js
44 lines (37 loc) · 1.41 KB
/
cactus.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
import {getCustomProperty, incrementCustomProperty, setCustomProperty} from "./updateCustomProperty.js";
const SPEED = 0.05;
const CACTUS_INTERVAL_MIN = 500;
const CACTUS_INTERVAL_MAX = 2000;
const worldElem = document.querySelector('[data-world]');
let nextCactusTime;
export function setupCactus() {
nextCactusTime = CACTUS_INTERVAL_MIN;
document.querySelectorAll('[data-cactus]').forEach(cactus => cactus.remove());
}
export function updateCactus(delta, speedScale) {
document.querySelectorAll('[data-cactus]').forEach(cactus => {
incrementCustomProperty(cactus, "--left", delta * speedScale * SPEED * -1);
if (getCustomProperty(cactus, "--left") < -100) {
cactus.remove();
}
});
if (nextCactusTime <= 0) {
createCactus();
nextCactusTime = randomNumBetween(CACTUS_INTERVAL_MIN, CACTUS_INTERVAL_MAX) / speedScale;
}
nextCactusTime -= delta;
}
export function getCactusRects() {
return [...document.querySelectorAll('[data-cactus]')].map(cactus => cactus.getBoundingClientRect());
}
function createCactus() {
const cactus = document.createElement('img');
cactus.dataset.cactus = true;
cactus.src = './assets/cactus.png';
cactus.classList.add('cactus');
setCustomProperty(cactus, "--left", 100);
worldElem.append(cactus);
}
function randomNumBetween(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}