-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
94 lines (79 loc) · 2.45 KB
/
main.js
File metadata and controls
94 lines (79 loc) · 2.45 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { setupGround } from './ground.js'
import { updateGround } from '/ground.js'
import { updateSpace, setupSpace, getSpaceRect, setSpaceLose } from '/Spaceboi.js'
import { updateMonster, setupMonster, getMonsterRects } from '/Monster.js'
const WORLD_WIDTH = 100
const WORLD_HEIGHT = 43
const SPEED_SCALE_INCREASE = .00001
const worldElem = document.querySelector('[data-world]')
const scoreElem = document.querySelector('[data-score]')
const startScreenElem = document.querySelector('[data-start-screen]')
setPixelToWorldScale()
window.addEventListener("resize", setPixelToWorldScale)
document.addEventListener("keydown", handleStart, { once: true })
let lastTime
let speedScale
let score
function update(time) {
if (lastTime == null) {
lastTime = time
window.requestAnimationFrame(update)
return
}
const delta = time - lastTime
updateGround(delta, speedScale)
updateSpace(delta,speedScale)
updateMonster(delta, speedScale)
updateSpeedScale(delta)
updateScore(delta)
if (checkLose()) return handleLose()
lastTime = time
window.requestAnimationFrame(update)
}
function checkLose() {
const spaceRect = getSpaceRect()
return getMonsterRects().some(rect => isCollision(rect, spaceRect))
}
function isCollision(rect1, rect2) {
return (
rect1.left < rect2.right &&
rect1.top < rect2.bottom &&
rect1.right > rect2.left &&
rect1.bottom > rect2.top
)
}
function updateSpeedScale(delta) {
speedScale += delta * SPEED_SCALE_INCREASE
}
function updateScore(delta) {
score += delta * 0.01
scoreElem.textContent = Math.floor(score)
}
function handleStart() {
lastTime = null
speedScale = 1
score = 0
setupGround()
setupSpace()
setupMonster()
startScreenElem.classList.add("hide")
window.requestAnimationFrame(update)
}
function handleLose() {
setSpaceLose()
setTimeout(() => {
document.addEventListener("keydown", handleStart, {once: true})
startScreenElem.classList.remove("hide")
}, 100)
}
function setPixelToWorldScale() {
let worldToPixelScale
if(window.innerWidth / window.innerHeight < WORLD_WIDTH / WORLD_HEIGHT)
{
worldToPixelScale = window.innerWidth / WORLD_WIDTH
} else {
worldToPixelScale = window.innerHeight / WORLD_HEIGHT
}
worldElem.style.width = `${WORLD_WIDTH * worldToPixelScale}px`
worldElem.style.height = `${WORLD_HEIGHT * worldToPixelScale}px`
}