-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdino.js
69 lines (55 loc) · 1.62 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
import { incrementCustomProperty, getCustomProperty, setCustomProperty } from "./updateCustomProperty.js"
const dinoElem = document.querySelector("[data-dino]")
const JUMP_SPEED = 0.45
const GRAVITY = .0015
const DINO_FRAME_COUNT = 2
const FRAME_TIME = 100
let isJumping
let dinoFrame
let currentFrameTime
let yVeloctiy
export function setupDino() {
isJumping = false
dinoFrame = 0
currentFrameTime = 0
yVeloctiy = 0
setCustomProperty(dinoElem, "--bottom", 0)
document.removeEventListener("keydown", onJump)
document.addEventListener("keydown", onJump)
}
export function updateDino(delta, speedIncreaser) {
handleRUN(delta, speedIncreaser)
handleJump(delta)
}
export function getDinoRect() {
return dinoElem.getBoundingClientRect()
}
export function setDinoLose() {
dinoElem.src = "imgs/dino-lose.png"
}
function handleRUN(delta, speedIncreaser) {
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 * speedIncreaser
}
function handleJump(delta) {
if (!isJumping) return
incrementCustomProperty(dinoElem, "--bottom", yVeloctiy * delta)
if (getCustomProperty(dinoElem, "--bottom") <= 0) {
setCustomProperty(dinoElem, "--bottom", 0)
isJumping = false
}
yVeloctiy -= GRAVITY * delta
}
function onJump(e) {
if (e.code !== "Space" || isJumping) return
yVeloctiy = JUMP_SPEED
isJumping = true
}