-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rocket.js
110 lines (89 loc) · 2.16 KB
/
Rocket.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
109
110
class Rocket {
constructor({
dna = new DNA(),
pos = createVector(width / 2, height - 10),
target
} = {}) {
this.dna = dna
this.target = target
this.acc = createVector()
this.vel = createVector()
this.pos = pos
this.completed = false
this.crashed = false
this.step = 0
}
draw() {
push()
noStroke()
if (this.crashed) {
fill(255, 0, 0, 150)
} else {
fill(255, 150)
}
// Move to the position of the rocket
translate(this.pos.x, this.pos.y)
// Rotate to face the direction the rocket is moving
rotate(this.vel.heading())
triangle(8, 0, -7, -5, -7, 5)
pop()
}
update() {
if (this.crashed || this.completed) {
return
}
// Check for collisions
const distanceToTarget = dist(
this.pos.x,
this.pos.y,
this.target.x,
this.target.y
)
if (distanceToTarget < 25) {
// Within the radius of target
this.completed = true
this.completedStep = this.step
// Move to center of target
this.pos = this.target.copy()
// Clear velocity and acceleration
this.vel.mult(0)
this.acc.mult(0)
}
if (
this.pos.x < 0 ||
this.pos.x > width ||
this.pos.y < 0 ||
this.pos.y > height
) {
// Gone off the screen
this.crashed = true
}
if (!this.crashed && !this.finished) {
// Apply force to acceleration from DNA
this.applyForce(this.dna.genes[this.step++])
// Apply acceleration to velocity
this.vel.add(this.acc)
// Update position based on velocity
this.pos.add(this.vel)
// Clear the acceleration
this.acc.mult(0)
}
}
applyForce(force) {
this.acc.add(force)
}
calculateFitness() {
const d = dist(this.pos.x, this.pos.y, this.target.x, this.target.y)
this.fitness = map(d, 0, width, width, 0)
// Big bonus for completing
if (this.completed) {
this.fitness *= 10
// Add an extra bonus for completing quickly
this.fitness += (DNA.lifespan - this.completedStep) * 5
}
// Big penalty for crashing
if (this.crashed) {
this.fitness /= 5
}
}
}