-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdino.js
72 lines (59 loc) · 1.54 KB
/
dino.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
import {
incrementCustomProperty,
setCustomProperty,
getCustomProperty,
} from "./updateCustomProperty.js"
const dinoElem = document.querySelector("[data-dino]")
const JUMP_SPEED = 0.45
const GRAVITY = 0.0015
const DINO_FRAME_COUNT = 2
const FRAME_TIME = 100
let isJumping
let dinoFrame
let currentFrameTime
let yVelocity
export function setupDino() {
isJumping = false
dinoFrame = 0
currentFrameTime = 0
yVelocity = 0
setCustomProperty(dinoElem, "--bottom", 0)
document.removeEventListener("click", onJump)
document.addEventListener("click", onJump)
}
export function updateDino(delta, speedScale) {
handleRun(delta, speedScale)
handleJump(delta)
}
export function getDinoRect() {
return dinoElem.getBoundingClientRect()
}
export function setDinoLose() {
dinoElem.src = "imgs/dino-lose.png"
}
function handleRun(delta, speedScale) {
if (isJumping) {
dinoElem.src = `imgs/dino-stationary.png`
return
}
if (currentFrameTime >= FRAME_TIME) {
dinoFrame = (dinoFrame + 1) % DINO_FRAME_COUNT
dinoElem.src = `imgs/dino-run-${dinoFrame}.png`
currentFrameTime -= FRAME_TIME
}
currentFrameTime += delta * speedScale
}
function handleJump(delta) {
if (!isJumping) return
incrementCustomProperty(dinoElem, "--bottom", yVelocity * delta)
if (getCustomProperty(dinoElem, "--bottom") <= 0) {
setCustomProperty(dinoElem, "--bottom", 0)
isJumping = false
}
yVelocity -= GRAVITY * delta
}
function onJump(e) {
if (e.code == "click" || isJumping) return
yVelocity = JUMP_SPEED
isJumping = true
}