-
Notifications
You must be signed in to change notification settings - Fork 1
/
collider.go
431 lines (375 loc) · 10.5 KB
/
collider.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
// Package collider provides simple collision detection and resolution
package collider
import (
"errors"
"fmt"
"image/color"
"math"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/ebitenutil"
vector "github.com/melonfunction/ebiten-vector"
)
// Vars
var (
ErrShapeNotFound = errors.New("Couldn't remove shape from SpatialHash; not found")
)
// Shape interface. It's probably not needed but it keeps code more readable.
type Shape interface {
GetPosition() *vector.Vector // get the position
GetBounds() (float64, float64, float64, float64)
Move(x, y float64) // move by amount
MoveTo(x, y float64) // move to position
SetHash(s *SpatialHash) // sets ref to hash
GetHash() *SpatialHash // gets ref to hash
SetParent(i interface{})
GetParent() interface{}
}
// CircleShape shape
type CircleShape struct {
// Center point
Pos *vector.Vector
Radius float64
SpatialHash *SpatialHash
Parent interface{}
}
// RectangleShape shape
type RectangleShape struct {
// Center point
Pos *vector.Vector
Width, Height float64
SpatialHash *SpatialHash
Parent interface{}
}
// PointShape is a RectangleShape but with 0 width and height
type PointShape struct{ *RectangleShape }
// Cell contains shapes
type Cell struct {
Shapes map[Shape]Shape
}
// CellCoord is a coordinate used to index the hash
type CellCoord struct {
X, Y int
}
// SpatialHash contains cells
type SpatialHash struct {
// Size of the grid/cell/partition
CellSize int
// Store shapes in a cell depending on their bounds
Hash map[CellCoord]*Cell
// Backref for shapes to find its containing cells
Backref map[Shape][]*Cell
}
// NewSpatialHash returns a new *SpatialHash
func NewSpatialHash(cellSize int) *SpatialHash {
return &SpatialHash{
CellSize: cellSize,
Hash: make(map[CellCoord]*Cell),
Backref: make(map[Shape][]*Cell),
}
}
// Add adds a shape to the spatial hash
func (s *SpatialHash) Add(shape Shape) {
x1, y1, x2, y2 := shape.GetBounds()
// make sure big shapes are constrained properly
xStep := x2 - x1
if xStep > float64(s.CellSize) {
xStep = float64(s.CellSize)
}
yStep := y2 - y1
if yStep > float64(s.CellSize) {
yStep = float64(s.CellSize)
}
for x := x1; x <= x2; x += xStep {
for y := y1; y <= y2; y += yStep {
hashPos := CellCoord{
int(math.Floor(x / float64(s.CellSize))),
int(math.Floor(y / float64(s.CellSize))),
}
if _, ok := s.Hash[hashPos]; !ok {
s.Hash[hashPos] = &Cell{Shapes: make(map[Shape]Shape)}
}
s.Hash[hashPos].Shapes[shape] = shape // add shape to cell
s.Backref[shape] = append(s.Backref[shape], s.Hash[hashPos]) // add cell to backref
if xStep == 0 || yStep == 0 {
goto done
}
}
}
done:
shape.SetHash(s)
}
// Remove removes a shape from the spatial hash
func (s *SpatialHash) Remove(shape Shape) error {
if cells, ok := s.Backref[shape]; ok {
for _, cell := range cells {
delete(cell.Shapes, shape)
}
delete(s.Backref, shape)
}
return ErrShapeNotFound
}
// GetCollisionCandidates returns a list of all shapes in the same cells as shape
func (s *SpatialHash) GetCollisionCandidates(shape Shape) []Shape {
shapesMap := make(map[Shape]struct{})
if cells, ok := s.Backref[shape]; ok {
for _, cell := range cells {
for _, sh := range cell.Shapes {
shapesMap[sh] = struct{}{}
}
}
}
delete(shapesMap, shape)
shapes := make([]Shape, 0)
for k := range shapesMap {
shapes = append(shapes, k)
}
return shapes
}
// CollisionData contains information about the collision
type CollisionData struct {
Other Shape
SeparatingVector *vector.Vector
}
func collisionRectRect(r1, r2 *RectangleShape) *vector.Vector {
r1Left, r1Up, r1Right, r1Down := r1.GetBounds()
r2Left, r2Up, r2Right, r2Down := r2.GetBounds()
if !(((r1Right >= r2Left && r1Right <= r2Right) || (r1Left >= r2Left && r1Left <= r2Right) || (r1Left >= r2Left && r1Right <= r2Right) || (r2Left >= r1Left && r2Right <= r1Right)) &&
((r1Up <= r2Down && r1Up >= r2Up) || (r1Down <= r2Down && r1Down >= r2Up) || (r1Up >= r2Up && r1Down <= r2Down) || (r2Up >= r1Up && r2Down <= r1Down))) {
return &vector.Vector{0, 0}
}
var dx, dy float64
if r1.Pos.X < r2.Pos.X {
dx = r2.Pos.X - r2.Width/2 - r1.Pos.X - r1.Width/2
} else {
dx = r2.Pos.X + r2.Width/2 - r1.Pos.X + r1.Width/2
}
if r1.Pos.Y < r2.Pos.Y {
dy = r2.Pos.Y - r2.Height/2 - r1.Pos.Y - r1.Height/2
} else {
dy = r2.Pos.Y + r2.Height/2 - r1.Pos.Y + r1.Height/2
}
if math.Abs(dx) < math.Abs(dy) {
dy = 0
} else {
dx = 0
}
return &vector.Vector{dx, dy}
}
func collisionRectCirc(r1 *RectangleShape, c1 *CircleShape) *vector.Vector {
// Check bbox of circle
rr := collisionRectRect(
r1,
&RectangleShape{
Pos: c1.Pos,
Width: c1.Radius * 2,
Height: c1.Radius * 2,
})
if rr.Length() == 0 {
return rr
}
// Get nearest corner, return if midpoint of c1 is inside rect
left, up, right, down := r1.GetBounds()
var co *vector.Vector
if r1.Pos.X > c1.Pos.X { // left
if r1.Pos.Y > c1.Pos.Y { // top
if c1.Pos.X > left || c1.Pos.Y > up {
return rr
}
co = vector.NewVector(left, up)
} else { // bottom
if c1.Pos.X > left || c1.Pos.Y < down {
return rr
}
co = vector.NewVector(left, down)
}
} else { // right
if r1.Pos.Y > c1.Pos.Y { // top
if c1.Pos.X < right || c1.Pos.Y > up {
return rr
}
co = vector.NewVector(right, up)
} else { // bottom
if c1.Pos.X < right || c1.Pos.Y < down {
return rr
}
co = vector.NewVector(right, down)
}
}
// Resolve circle/point collision
cc := collisionCircCirc(
&CircleShape{
Pos: co,
Radius: 0,
},
c1)
return cc
}
func collisionCircCirc(c1, c2 *CircleShape) *vector.Vector {
dist := c1.Pos.Sub(c2.Pos)
depth := c1.Radius + c2.Radius - dist.Length()
if depth < 0 {
return &vector.Vector{0, 0}
}
return dist.Normalize().Mult(depth)
}
// CheckCollisions returns a list of all shapes and their separating vector.vector
func (s *SpatialHash) CheckCollisions(shape Shape) []CollisionData {
collisions := make([]CollisionData, 0)
candidates := s.GetCollisionCandidates(shape)
switch typed := shape.(type) {
case *RectangleShape:
for _, candidate := range candidates {
var col *vector.Vector
switch other := candidate.(type) {
case *RectangleShape:
col = collisionRectRect(typed, other)
case *CircleShape:
col = collisionRectCirc(typed, other)
default:
// TODO error
}
if col != nil && col.Length() > 0 {
collisions = append(collisions, CollisionData{Other: candidate, SeparatingVector: col})
}
}
case *CircleShape:
for _, candidate := range candidates {
var col *vector.Vector
switch other := candidate.(type) {
case *RectangleShape:
col = collisionRectCirc(other, typed).Mult(-1)
case *CircleShape:
col = collisionCircCirc(typed, other)
default:
// TODO error
}
if col != nil && col.Length() > 0 {
collisions = append(collisions, CollisionData{Other: candidate, SeparatingVector: col})
}
}
default:
// TODO error
}
return collisions
}
// Draw is a debug function. It draws a rectangle for every cell which has had a shape in it at some point.
func (s *SpatialHash) Draw(surface *ebiten.Image) {
for pos, cell := range s.Hash {
x, y, w := float64(pos.X*s.CellSize), float64(pos.Y*s.CellSize), float64(s.CellSize)
color := color.RGBA{255, 255, 255, 255}
ebitenutil.DrawLine(surface, x, y, x+w, y, color)
ebitenutil.DrawLine(surface, x, y, x, y+w, color)
ebitenutil.DrawLine(surface, x, y+w, x+w, y+w, color)
ebitenutil.DrawLine(surface, x+w, y, x+w, y+w, color)
ebitenutil.DebugPrintAt(surface, fmt.Sprintf("%d", len(cell.Shapes)), pos.X*s.CellSize, pos.Y*s.CellSize)
}
}
// NewCircleShape creates, then adds a new CircleShape to the hash before returning it
func (s *SpatialHash) NewCircleShape(x, y, r float64) *CircleShape {
ci := &CircleShape{
Pos: &vector.Vector{x, y},
Radius: r,
}
s.Add(ci)
return ci
}
// GetPosition returns the Point of the CircleShape
func (ci *CircleShape) GetPosition() *vector.Vector {
return ci.Pos
}
// GetBounds returns the Bounds of the CircleShape
func (ci *CircleShape) GetBounds() (float64, float64, float64, float64) {
return ci.Pos.X - ci.Radius,
ci.Pos.Y - ci.Radius,
ci.Pos.X + ci.Radius,
ci.Pos.Y + ci.Radius
}
// Move moves the CircleShape by x and y
func (ci *CircleShape) Move(x, y float64) {
ci.Pos.X += x
ci.Pos.Y += y
hash := ci.GetHash()
hash.Remove(ci)
hash.Add(ci)
}
// MoveTo moves the CircleShape to x and y
func (ci *CircleShape) MoveTo(x, y float64) {
ci.Pos.X = x
ci.Pos.Y = y
hash := ci.GetHash()
hash.Remove(ci)
hash.Add(ci)
}
// SetHash sets the hash
func (ci *CircleShape) SetHash(s *SpatialHash) {
ci.SpatialHash = s
}
// GetHash gets the hash
func (ci *CircleShape) GetHash() *SpatialHash {
return ci.SpatialHash
}
// SetParent sets the parent
func (ci *CircleShape) SetParent(i interface{}) {
ci.Parent = i
}
// GetParent gets the parent
func (ci *CircleShape) GetParent() interface{} {
return ci.Parent
}
// NewRectangleShape creates, then adds a new RectangleShape to the hash before returning it
func (s *SpatialHash) NewRectangleShape(x, y, w, h float64) *RectangleShape {
re := &RectangleShape{
Pos: &vector.Vector{x, y},
Width: w,
Height: h,
}
s.Add(re)
return re
}
// GetPosition returns the Point of the RectangleShape
func (re *RectangleShape) GetPosition() *vector.Vector {
return re.Pos
}
// GetBounds returns the Bounds of the RectangleShape
func (re *RectangleShape) GetBounds() (float64, float64, float64, float64) {
return re.Pos.X - re.Width/2,
re.Pos.Y - re.Height/2,
re.Pos.X + re.Width/2,
re.Pos.Y + re.Height/2
}
// Move moves the RectangleShape by x and y
func (re *RectangleShape) Move(x, y float64) {
re.Pos.X += x
re.Pos.Y += y
hash := re.GetHash()
hash.Remove(re)
hash.Add(re)
}
// MoveTo moves the RectangleShape to x and y
func (re *RectangleShape) MoveTo(x, y float64) {
re.Pos.X = x
re.Pos.Y = y
hash := re.GetHash()
hash.Remove(re)
hash.Add(re)
}
// SetHash sets the hash
func (re *RectangleShape) SetHash(s *SpatialHash) {
re.SpatialHash = s
}
// GetHash gets the hash
func (re *RectangleShape) GetHash() *SpatialHash {
return re.SpatialHash
}
// SetParent sets the parent
func (re *RectangleShape) SetParent(i interface{}) {
re.Parent = i
}
// GetParent gets the parent
func (re *RectangleShape) GetParent() interface{} {
return re.Parent
}
// NewPointShape creates, then adds a new RectangleShape to the hash before returning it
func (s *SpatialHash) NewPointShape(x, y float64) *PointShape {
return &PointShape{s.NewRectangleShape(x, y, 0, 0)}
}