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
use bevy_math::{Vec2, Vec3};
#[derive(Debug)]
pub enum Collision {
Left,
Right,
Top,
Bottom,
}
pub fn collide(a_pos: Vec3, a_size: Vec2, b_pos: Vec3, b_size: Vec2) -> Option<Collision> {
let a_min = a_pos.truncate() - a_size / 2.0;
let a_max = a_pos.truncate() + a_size / 2.0;
let b_min = b_pos.truncate() - b_size / 2.0;
let b_max = b_pos.truncate() + b_size / 2.0;
if a_min.x() < b_max.x()
&& a_max.x() > b_min.x()
&& a_min.y() < b_max.y()
&& a_max.y() > b_min.y()
{
let (x_collision, x_depth) =
if a_min.x() < b_min.x() && a_max.x() > b_min.x() && a_max.x() < b_max.x() {
(Some(Collision::Left), b_min.x() - a_max.x())
} else if a_min.x() > b_min.x() && a_min.x() < b_max.x() && a_max.x() > b_max.x() {
(Some(Collision::Right), a_min.x() - b_max.x())
} else {
(None, 0.0)
};
let (y_collision, y_depth) =
if a_min.y() < b_min.y() && a_max.y() > b_min.y() && a_max.y() < b_max.y() {
(Some(Collision::Bottom), b_min.y() - a_max.y())
} else if a_min.y() > b_min.y() && a_min.y() < b_max.y() && a_max.y() > b_max.y() {
(Some(Collision::Top), a_min.y() - b_max.y())
} else {
(None, 0.0)
};
match (x_collision, y_collision) {
(Some(x_collision), Some(y_collision)) => {
if y_depth < x_depth {
Some(y_collision)
} else {
Some(x_collision)
}
}
(Some(x_collision), None) => Some(x_collision),
(None, Some(y_collision)) => Some(y_collision),
(None, None) => None,
}
} else {
None
}
}