-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
108 lines (89 loc) · 2.09 KB
/
index.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
const canvasWidth = Math.min(
window.innerWidth,
config.maxCanvasWidth,
)
const canvasHeight = window.innerHeight
const { requestAnimationFrame } = window
let prevTime = 0
const render = (game, time) => {
const {
ctx,
player,
} = game
const speed = getSpeed(game)
const { fps } = config
if (time - prevTime > 1000 / fps) {
clearCanvas(ctx)
moveRoad(game)
drawRoad(game)
updateSpeed(game, speed)
outputCurrentInfo(game)
player.move(game)
player.draw(ctx)
controlEnemies(game)
controlExplosions(game)
checkEnemiesCollisions(game)
prevTime = time
}
requestAnimationFrame((time) => render(game, time))
}
const checkEnemiesCollisions = (game) => {
const {
player,
objects: { enemies = []},
} = game
enemies.forEach((enemy) => {
const isCollision = checkCollisions(player, enemy, Player, Enemy)
if (isCollision) onCarCrash(game)
})
}
const crashAudioElm = document.getElementById('crashAudio')
const onCarCrash = (game) => {
removeSpeedInterval(game)
setSpeed(game, 0)
}
const clearCanvas = (ctx) => {
ctx.clearRect(0, 0, canvasWidth, canvasHeight)
}
window.onload = () => {
const canvas = document.getElementById('canvas')
canvas.width = canvasWidth
canvas.height = canvasHeight
const ctx = canvas.getContext('2d')
const playerX = (canvasWidth - Player.width) / 2 - 10
const playerY = (canvasHeight - Player.height) - 50
const player = new Player(playerX, playerY)
const game = {
ctx,
canvas: {
width: canvasWidth,
height: canvasHeight,
},
control: {
pedals: {
gas: false,
brake: false,
},
prevPedal: 'gas',
turn: {
left: false,
right: false,
},
},
player,
objects: {
enemies: [],
trees: [],
explosions: [],
},
road: [],
score: {
distance: 0,
circles: [],
},
}
setSpeed(game, 20)
addEventListener('keydown', (e) => player.moveCarByEvent.bind(player)(e, game))
addEventListener('keyup', (e) => player.stopKeyEvent.bind(player)(e, game))
render(game)
}