Skip to content

Commit 4f76b89

Browse files
committed
REVIEWED: CheckCollisionLines(), formating and follow raylib conventions
1 parent 3881d2a commit 4f76b89

1 file changed

Lines changed: 19 additions & 15 deletions

File tree

src/rshapes.c

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2363,32 +2363,36 @@ bool CheckCollisionCircleRec(Vector2 center, float radius, Rectangle rec)
23632363
}
23642364

23652365
// Check the collision between two lines defined by two points each, returns collision point by reference
2366+
// REF: https://en.wikipedia.org/wiki/Line–line_intersection#Given_two_points_on_each_line_segment
23662367
bool CheckCollisionLines(Vector2 startPos1, Vector2 endPos1, Vector2 startPos2, Vector2 endPos2, Vector2 *collisionPoint)
23672368
{
2368-
// According to https://en.wikipedia.org/wiki/Line–line_intersection#Given_two_points_on_each_line_segment
2369+
bool collision = false;
2370+
23692371
float rx = endPos1.x - startPos1.x;
23702372
float ry = endPos1.y - startPos1.y;
23712373
float sx = endPos2.x - startPos2.x;
23722374
float sy = endPos2.y - startPos2.y;
23732375

2374-
float div = rx * sy - ry * sx;
2375-
2376-
if (fabsf(div) < FLT_EPSILON) {
2377-
return false;
2378-
}
2376+
float div = rx*sy - ry*sx;
23792377

2380-
float s12x = startPos2.x - startPos1.x;
2381-
float s12y = startPos2.y - startPos1.y;
2378+
if (fabsf(div) >= FLT_EPSILON)
2379+
{
2380+
float s12x = startPos2.x - startPos1.x;
2381+
float s12y = startPos2.y - startPos1.y;
23822382

2383-
float t = (s12x * sy - s12y * sx) / div;
2384-
float u = (s12x * ry - s12y * rx) / div;
2383+
float t = (s12x*sy - s12y*sx)/div;
2384+
float u = (s12x*ry - s12y*rx)/div;
23852385

2386-
if (0.0f <= t && t <= 1.0f && 0.0f <= u && u <= 1.0f) {
2387-
collisionPoint->x = startPos1.x + t * rx;
2388-
collisionPoint->y = startPos1.y + t * ry;
2389-
return true;
2386+
if ((0.0f <= t) && (t <= 1.0f) && (0.0f <= u) && (u <= 1.0f))
2387+
{
2388+
collisionPoint->x = startPos1.x + t*rx;
2389+
collisionPoint->y = startPos1.y + t*ry;
2390+
2391+
collision = true;
2392+
}
23902393
}
2391-
return false;
2394+
2395+
return collision;
23922396
}
23932397

23942398
// Check if point belongs to line created between two points [p1] and [p2] with defined margin in pixels [threshold]

0 commit comments

Comments
 (0)