forked from cetz-package/cetz
-
Notifications
You must be signed in to change notification settings - Fork 0
/
collisions.typ
63 lines (54 loc) · 1.92 KB
/
collisions.typ
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
// NOTE: this file is to be used for finding intersections of paths. It is currently not in use but could be fully implemented at a later date.
#import "vector.typ"
// http://paulbourke.net/geometry/pointlineplane/ Intersection point of two line segments in 2 dimensions
// http://jeffreythompson.org/collision-detection/poly-poly.php
// Returns the (x,y) coordinates of the intersection or none if the lines do not collide
#let line-line(x1, y1, x2, y2, x3, y3, x4, y4) = {
let denominator = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)
if denominator == 0 {
// lines are parallel or coincident
return none
}
let uA = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denominator
let uB = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denominator
return if (uA >= 0 and uA <= 1 and uB >= 0 and uB <= 1) {
(
x1 + uA * (x2 - x1),
y1 + uA * (y2 - y1)
)
}
}
// Returns the (x,y) coordinates of the intersections or none if the polygon and line do not collide
// Assumes the polygon is not closed. If the polygon is closed add the first vertex to the end of the vertex list
#let poly-line(vertices, x1, y1, x2, y2) = {
for current in range(vertices.len() - 1) {
let next = current + 1
let (x3, y3, x4, y4) = (
vertices.at(current).at(0),
vertices.at(current).at(1),
vertices.at(next).at(0),
vertices.at(next).at(1),
)
let collision = line-line(x1, y1, x2, y2, x3, y3, x4, y4)
if collision != none {
collision
}
}
}
#let poly-poly(p1, p2) = {
let intersections = ()
for current in range(p1.len() - 1) {
let next = current + 1
let (x1, y1, x2, y2) = (
p1.at(current).at(0),
p1.at(current).at(1),
p1.at(next).at(0),
p1.at(next).at(1)
)
let collision = poly-line(p2, x1, y1, x2, y2)
if collision != none and not collision in intersections {
intersections.push(collision)
}
}
return intersections
}