-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroad.js
More file actions
132 lines (107 loc) · 2.53 KB
/
road.js
File metadata and controls
132 lines (107 loc) · 2.53 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
const roadWidth = 400
const roadImg = document.getElementById('img-road')
class RoadPart {
constructor(game, x, y) {
const {
canvas: {
width: canvasWidth,
height: canvasHeight,
},
} = game
const roadX = (x !== undefined) ? x : (canvasWidth - roadWidth) / 2
const roadY = (y !== undefined) ? y : 0
this.x = roadX
this.y = roadY
this.roadHeight = canvasHeight
}
draw(ctx) {
ctx.drawImage(
roadImg,
0, 0,
400, 400,
this.x, this.y,
roadWidth, this.roadHeight
)
}
move(game) {
const speed = getSpeed(game)
this.y += speed
if (this.y >= this.roadHeight) {
const anotherPart = getNeighborPart(game, this)
this.y = anotherPart.y - this.roadHeight + speed
}
}
}
const getNeighborPart = (game, somePart) => {
const { road } = game
return road.find((part) => part !== somePart)
}
const drawRoad = (game) => {
const {
ctx,
canvas: {
height: canvasHeight,
},
road,
} = game
if (!road.length) {
const roadPart1 = new RoadPart(game)
const roadPart2 = new RoadPart(game, undefined, canvasHeight)
road.push(roadPart1, roadPart2)
}
const roadsideWidth = getRoadsideWidth(game)
const roadWidth = getRoadWidth()
ctx.fillStyle = '#494948'
ctx.fillRect(
roadsideWidth, 0,
roadWidth, 100
)
road.forEach((part) => {
part.draw(ctx)
})
controlTrees(game)
}
const getRoadWidth = () => {
return roadWidth
}
const moveRoad = (game) => {
if (!game.road) return
const {
road = [],
objects: { trees = [] },
} = game
road.forEach((part) => {
part.move(game)
})
trees.forEach((tree) => {
tree.move(game)
})
}
const treeImg = document.getElementById('img-tree')
class Tree {
constructor(game) {
const { canvas: { width: canvasWidth }} = game
const roadWidth = getRoadWidth()
const roadsideWidth = (canvasWidth - roadWidth) / 2
const side = Math.random() > 0.5 ? 'rigth' : 'left'
const x = Math.random() * (roadsideWidth - Tree.width)
this.x = side === 'left' ? x : roadWidth + roadsideWidth + x
this.y = -Tree.height
this.image = treeImg
}
move(game) {
const speed = getSpeed(game)
const { y } = this
const { height: canvasHeight } = getCanvasProps(game)
this.y += speed
if (this.y > canvasHeight) {
this.y = this.y - canvasHeight - Tree.height
}
}
draw(ctx) {
const { x, y } = this
ctx.drawImage(this.image, x, y, Tree.width, Tree.height)
}
}
Tree.width = 50
Tree.height = 100