Skip to content

Commit 88e5b6c

Browse files
committed
Collision detection functions
1 parent f810c44 commit 88e5b6c

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

collision.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package geom
2+
3+
// CollisionRectangles checks if the given rectangles collide.
4+
func CollisionRectangles[T Number](r1 Rectangle[T], r2 Rectangle[T]) bool {
5+
// TODO: support rotation
6+
7+
min1, max1 := r1.Min(), r1.Max()
8+
min2, max2 := r2.Min(), r2.Max()
9+
10+
return min1.X <= max2.X && min2.X <= max1.X && min1.Y <= max2.Y && min2.Y <= max1.Y
11+
}
12+
13+
// CollisionRectangleCircle checks if the given rectangle and circle collide.
14+
func CollisionRectangleCircle[T Number](r Rectangle[T], c Circle[T]) bool {
15+
// TODO: support rotation
16+
17+
distance := c.Center.Subtract(r.Center).Abs()
18+
extends := r.Size.Scale(0.5).ToVector()
19+
20+
// circle center is more than size outside rectangle borders
21+
if distance.X > extends.X+c.Radius || distance.Y > extends.Y+c.Radius {
22+
return false
23+
}
24+
25+
// circle center is in rectangle
26+
if distance.X <= extends.X || distance.Y <= extends.Y {
27+
return true
28+
}
29+
30+
// circle center is less than its size outside nearest border
31+
return distance.Subtract(extends).Less(c.Radius)
32+
}
33+
34+
// CollisionCircles checks if the given circles collide.
35+
func CollisionCircles[T Number](c1 Circle[T], c2 Circle[T]) bool {
36+
distance := c1.Center.Subtract(c2.Center)
37+
threshold := c1.Radius + c2.Radius
38+
39+
return distance.Less(threshold)
40+
}

size.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,11 @@ func (s Size[T]) XY() (T, T) {
7575
return s.Width, s.Height
7676
}
7777

78+
// ToVector converts the size to a Vector.
79+
func (s Size[T]) ToVector() Vector[T] {
80+
return Vector[T]{s.Width, s.Height}
81+
}
82+
7883
// String returns a string in the form "WxH" using the underlying number formatting.
7984
func (s Size[T]) String() string {
8085
return fmt.Sprintf("%sx%s", ToString(s.Width), ToString(s.Height))

0 commit comments

Comments
 (0)