-
Notifications
You must be signed in to change notification settings - Fork 0
/
cactus.js
53 lines (46 loc) · 1.38 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
45
46
47
48
49
50
51
52
53
import {
setCustomProperty,
incrementCustomProperty,
getCustomProperty,
} 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 =
randomNumberBetween(CACTUS_INTERVAL_MIN, CACTUS_INTERVAL_MAX) / speedScale
}
nextCactusTime -= delta
}
export function getCactusRects() {
return [...document.querySelectorAll("[data-cactus]")].map(cactus => {
return cactus.getBoundingClientRect()
})
}
function createCactus() {
const cactus = document.createElement("img")
cactus.dataset.cactus = true
cactus.src = "imgs/cactus.png"
cactus.classList.add("cactus")
setCustomProperty(cactus, "--left", 100)
worldElem.append(cactus)
}
function randomNumberBetween(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min)
}