Skip to content

Commit 0d814e1

Browse files
committed
Fix #165
1 parent 2d60e20 commit 0d814e1

File tree

4 files changed

+32
-9
lines changed

4 files changed

+32
-9
lines changed

src/collisions.c

+28-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// line to line is stolen from: http://jeffreythompson.org/collision-detection/table_of_contents.php
2+
#include <float.h>
23
#include <math.h>
34
#include <stdbool.h>
45
#include <stdio.h>
@@ -42,14 +43,37 @@ th_point_to_quad(th_vf2 p, th_quad *q, th_vf2 *ic)
4243
return coll;
4344
}
4445

46+
static fu
47+
point_distance(th_vf2 a, th_vf2 b)
48+
{
49+
a.x -= b.x;
50+
a.y -= b.y;
51+
return a.x * a.x + a.y * a.y;
52+
}
53+
4554
uu
4655
th_line_to_quad(th_vf2 b, th_vf2 e, th_quad *q, th_vf2 *ic)
4756
{
48-
for (uu i = 0; i < 4; i++)
49-
if (th_line_to_line(b, e, q->v[i], q->v[(i + 1) % 4], ic))
50-
return 1;
57+
th_vf2 ic_c; // closest incident point
58+
float ic_d = FLT_MAX; // incident distance
59+
bool collision = false;
5160

52-
return 0;
61+
for (uu i = 0; i < 4; i++) {
62+
th_vf2 ic_n; // current incident point
63+
64+
if (th_line_to_line(b, e, q->v[i], q->v[(i + 1) % 4], &ic_n)) {
65+
float ic_nd = point_distance(b, ic_n);
66+
if (ic_nd < ic_d) {
67+
ic_d = ic_nd;
68+
ic_c = ic_n;
69+
}
70+
collision = true;
71+
}
72+
}
73+
74+
*ic = ic_c;
75+
76+
return collision;
5377
}
5478

5579
uu

src/raycast.c

+2-3
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,8 @@ th_ray_getcoll(
1111
for (int i = 0; i < sceneLen && *collCount < maxColls; i++) {
1212
th_quad q = th_ent_transform(scene[i]);
1313

14-
if (th_line_to_quad(ra->pos, p2, &q, &colls[*collCount].pos) ||
15-
// in case the ray is completely inside the quad
16-
th_point_to_quad(ra->pos, &q, &colls[*collCount].pos)) {
14+
if (th_point_to_quad(ra->pos, &q, &colls[*collCount].pos) ||
15+
th_line_to_quad(ra->pos, p2, &q, &colls[*collCount].pos)) {
1716
++(*collCount);
1817
}
1918
}

0 commit comments

Comments
 (0)