-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
collision_detection.ts
90 lines (81 loc) · 1.66 KB
/
collision_detection.ts
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
/**
* Detects collision between 2 boxes.
*/
export function boxBoxCollision(
oneX: number,
oneY: number,
oneWidth: number,
oneHeight: number,
twoX: number,
twoY: number,
twoWidth: number,
twoHeight: number
) {
return !(
oneY + oneHeight < twoY ||
oneY > twoY + twoHeight ||
oneX > twoX + twoWidth ||
oneX + oneWidth < twoX
);
}
/**
* Detects collision between two circles.
*/
export function circleCircleCollision(
x1: number,
y1: number,
radius1: number,
x2: number,
y2: number,
radius2: number
) {
const distX = x1 - x2;
const distY = y1 - y2;
if (
Math.pow(distX, 2) + Math.pow(distY, 2) <=
Math.pow(radius1 + radius2, 2)
) {
return true;
}
return false;
}
/**
* Detects collision between a circle and a point.
*/
export function circlePointCollision(
circleX: number,
circleY: number,
circleRadius: number,
pointX: number,
pointY: number
) {
const distanceX = circleX - pointX;
const distanceY = circleY - pointY;
// pythagoras
const squareDistance = distanceX * distanceX + distanceY * distanceY;
if (squareDistance <= circleRadius * circleRadius) {
return true;
}
return false;
}
/**
* Detects collision between a point and a box.
*/
export function pointBoxCollision(
pointX: number,
pointY: number,
boxX: number,
boxY: number,
boxWidth: number,
boxHeight: number
) {
if (
pointX < boxX ||
pointX > boxX + boxWidth ||
pointY < boxY ||
pointY > boxY + boxHeight
) {
return false;
}
return true;
}