-
Notifications
You must be signed in to change notification settings - Fork 0
/
physics.go
54 lines (47 loc) · 1.48 KB
/
physics.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
package raylibcollision
import rl "github.com/gen2brain/raylib-go/raylib"
// CollideWithRects is a utility function and checks whether a rectangle collided with some rectangle in the array or not.
// It returns a hit slice that includes all the collided rectangles.
func CollideWithRects(rect rl.Rectangle, rects []rl.Rectangle) []rl.Rectangle {
var hitSlice []rl.Rectangle
for _, rec := range rects {
if CollideWithRect(rect, rec) {
hitSlice = append(hitSlice, rec)
}
}
return hitSlice
}
type collisionDirection struct {
Top bool
Bottom bool
Right bool
Left bool
}
// MoveRect will handle the collision and return the direction struct, which includes boolean values of the directions.
// The function checks the future movement whether it collided with some rectangle in the passed slice.
func MoveRect(rect *rl.Rectangle, dx, dy float32, rects []rl.Rectangle) collisionDirection {
collision := collisionDirection{Top: false, Bottom: false, Right: false, Left: false}
rect.X += dx
hitList := CollideWithRects(*rect, rects)
for _, tile := range hitList {
if dx > 0 {
rect.X = tile.X - rect.Width
collision.Right = true
} else if dx < 0 {
rect.X = tile.X + tile.Width
collision.Left = true
}
}
rect.Y += dy
hitList = CollideWithRects(*rect, rects)
for _, tile := range hitList {
if dy > 0 {
rect.Y = tile.Y - rect.Height
collision.Bottom = true
} else if dy < 0 {
rect.Y = tile.Y + tile.Height
collision.Top = true
}
}
return collision
}