-
Notifications
You must be signed in to change notification settings - Fork 0
/
collision.go
98 lines (86 loc) · 2.16 KB
/
collision.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
package main
import (
"math/cmplx"
"sort"
)
type Collidable interface {
// these methods are defined on type Entity
Position() complex128
Velocity() complex128
SetVelocity(complex128)
Visible() bool
SetVisible(bool)
Health() int
SetHealth(int)
LastHit() Collidable
SetLastHit(Collidable)
// implement these methods on the concrete types
Radius() float64
Team() int // Objects in the same Team() will not do damage with each other
BodyDamage() int
CanAcquireExperience() bool // whether the entity can get experience by killing others
AcquireExperience(int)
RewardingExperience() int
}
func Collide(a, b Collidable) {
dist, phi := cmplx.Polar(a.Position() - b.Position())
rsum := a.Radius() + b.Radius()
if dist > rsum {
return
}
a.SetVelocity(a.Velocity() + cmplx.Rect((rsum-dist)/rsum+0.1, phi))
b.SetVelocity(b.Velocity() + cmplx.Rect((dist-rsum)/rsum+0.1, phi))
if a.Team() != b.Team() {
Hit(a, b)
Hit(b, a)
}
}
func Hit(a, b Collidable) {
hp := b.Health()
hp -= a.BodyDamage()
b.SetHealth(hp)
if a.CanAcquireExperience() {
b.SetLastHit(a)
}
if hp <= 0 {
b.SetVisible(false)
if b.LastHit() != nil {
b.LastHit().AcquireExperience(b.RewardingExperience())
}
}
}
func leftBound(c Collidable) float64 {
return real(c.Position()) - c.Radius()
}
func rightBound(c Collidable) float64 {
return real(c.Position()) + c.Radius()
}
func topBound(c Collidable) float64 {
return imag(c.Position()) + c.Radius()
}
func bottomBound(c Collidable) float64 {
return imag(c.Position()) - c.Radius()
}
type ByX []Collidable
func (a ByX) Len() int { return len(a) }
func (a ByX) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByX) Less(i, j int) bool { return leftBound(a[i]) < leftBound(a[j]) }
func DoCollision(a []Collidable) {
sort.Sort(ByX(a))
var pairs [][2]Collidable
for i, left := range a {
for j := i + 1; j < len(a); j++ {
right := a[j]
if leftBound(right) < rightBound(left) {
if bottomBound(right) < topBound(left) && bottomBound(left) < topBound(right) {
pairs = append(pairs, [2]Collidable{left, right})
}
} else {
break
}
}
}
for _, pair := range pairs {
Collide(pair[0], pair[1])
}
}