-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcollision.go
91 lines (79 loc) · 2.03 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
package kar
import (
"math"
)
// Overlaps checks if the rectangle overlaps with another rectangle
func Overlaps(p1 *Position, s1 *Size, p2 *Position, s2 *Size) bool {
return p1.X+s1.W > p2.X && p2.X+s2.W > p1.X && p1.Y+s1.H > p2.Y && p2.Y+s2.H > p1.Y
}
func CheckCollision(p1 *Position, s1 *Size, v1 *Velocity, p2 *Position, s2 *Size) CollisionInfo {
info := CollisionInfo{
Normal: [2]int{0, 0},
}
// Önce statik çarpışma kontrolü
if Overlaps(p1, s1, p2, s2) {
info.Collided = true
// Statik çarpışmada itme yönünü belirle
centerX1 := p1.X + s1.W/2
centerX2 := p2.X + s2.W/2
centerY1 := p1.Y + s1.H/2
centerY2 := p2.Y + s2.H/2
diffX := centerX1 - centerX2
diffY := centerY1 - centerY2
// Hangi eksende daha az örtüşme var ise o yönde it
overlapX := s1.W/2 + s2.W/2 - math.Abs(diffX)
overlapY := s1.H/2 + s2.H/2 - math.Abs(diffY)
if overlapX < overlapY {
if diffX > 0 {
info.Normal[0] = 1
info.DeltaX = overlapX
} else {
info.Normal[0] = -1
info.DeltaX = -overlapX
}
} else {
if diffY > 0 {
info.Normal[1] = 1
info.DeltaY = overlapY
} else {
info.Normal[1] = -1
info.DeltaY = -overlapY
}
}
return info
}
// Hareket varsa dinamik çarpışma kontrolü
if math.Abs(v1.X) > 0 || math.Abs(v1.Y) > 0 {
nextPos := &Position{p1.X + v1.X, p1.Y + v1.Y}
// Önce X ekseninde hareket et ve kontrol et
if Overlaps(p2, s2, nextPos, s1) {
info.Collided = true
if v1.X > 0 {
info.DeltaX = p2.X - (nextPos.X + s1.W)
info.Normal[0] = -1
} else if v1.X < 0 {
info.DeltaX = (p2.X + s2.W) - nextPos.X
info.Normal[0] = 1
}
return info
}
// Sonra Y ekseninde hareket et ve kontrol et
if Overlaps(p2, s2, nextPos, s1) {
info.Collided = true
if v1.Y > 0 {
info.DeltaY = p2.Y - (nextPos.Y + s1.H)
info.Normal[1] = -1
} else if v1.Y < 0 {
info.DeltaY = (p2.Y + s2.H) - nextPos.Y
info.Normal[1] = 1
}
}
}
return info
}
type CollisionInfo struct {
Normal [2]int
DeltaX float64
DeltaY float64
Collided bool
}