/
goid.go
121 lines (105 loc) · 2.36 KB
/
goid.go
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
package goids
import "math"
type ImageType int
const (
Front ImageType = iota
Side
Pink
)
const GopherSize = 32
type Goid struct {
position Vector
velocity Vector
acceleration Vector
maxSpeed float64
maxForce float64
sight float64
imageType ImageType
}
func (g *Goid) Seek(t Vector) {
tv := Sub(t, g.position)
tv.Limit(g.maxSpeed)
force := Sub(tv, g.velocity)
g.acceleration.Add(force)
}
func (g *Goid) Flee(t Vector) {
tv := Sub(t, g.position)
tv.Limit(g.maxSpeed)
force := Sub(tv, g.velocity)
g.acceleration.Sub(force)
}
func (g Goid) IsInsight(g2 Goid) bool {
d := Sub(g.position, g2.position).Len()
return d < g.sight
}
func (g *Goid) Align(goids []Goid) {
var avgVel Vector
n := 0
for _, other := range goids {
if g == &other || !g.IsInsight(other) {
continue
}
avgVel.Add(other.velocity)
n++
}
if n > 0 {
avgVel.ScalarMul(1 / float64(n))
avgVel.Limit(g.maxSpeed)
g.acceleration.Add(Sub(avgVel, g.velocity))
}
}
func (g *Goid) Separate(goids []Goid) {
for _, other := range goids {
if g == &other || !g.IsInsight(other) {
continue
}
d := Sub(g.position, other.position).Len()
if d < 50 {
g.Flee(other.position)
}
}
}
func (g *Goid) Cohesive(goids []Goid) {
var avgPos Vector
n := 0
for _, other := range goids {
if g == &other || !g.IsInsight(other) {
continue
}
avgPos.Add(other.position)
n++
}
if n > 0 {
avgPos.ScalarMul(1 / float64(n))
g.Seek(avgPos)
}
}
func (g *Goid) Flock(goids []Goid) {
g.Align(goids)
g.Separate(goids)
g.Cohesive(goids)
}
func (g *Goid) AdjustEdge(width, height float64) {
if g.position.X < float64(GopherSize)/2 {
g.position.X = float64(GopherSize) / 2
g.velocity.X = math.Abs(g.velocity.X)
} else if g.position.X >= width-float64(GopherSize)/2 {
g.position.X = width - float64(GopherSize)/2 - 1
g.velocity.X = -math.Abs(g.velocity.X)
}
if g.position.Y < float64(GopherSize)/2 {
g.position.Y = float64(GopherSize) / 2
g.velocity.Y = math.Abs(g.velocity.Y)
} else if g.position.Y >= height-float64(GopherSize)/2 {
g.position.Y = height - float64(GopherSize)/2 - 1
g.velocity.Y = -math.Abs(g.velocity.Y)
}
}
func (g *Goid) Update(width, height float64) {
g.acceleration.Limit(g.maxForce)
g.velocity.Add(g.acceleration)
g.velocity.Limit(g.maxSpeed)
g.position.Add(g.velocity)
g.acceleration.ScalarMul(0)
g.AdjustEdge(width, height)
}