From 925e369c8960f8fd644f192bffb819c215f49368 Mon Sep 17 00:00:00 2001 From: kai-z99 Date: Wed, 29 May 2024 18:24:27 -0700 Subject: [PATCH] inital function --- src/raylib.h | 1 + src/rshapes.c | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/raylib.h b/src/raylib.h index b870cc6ca..1758e7b80 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -1295,6 +1295,7 @@ RLAPI bool CheckCollisionPointTriangle(Vector2 point, Vector2 p1, Vector2 p2, Ve RLAPI bool CheckCollisionPointPoly(Vector2 point, Vector2 *points, int pointCount); // Check if point is within a polygon described by array of vertices RLAPI bool CheckCollisionLines(Vector2 startPos1, Vector2 endPos1, Vector2 startPos2, Vector2 endPos2, Vector2 *collisionPoint); // Check the collision between two lines defined by two points each, returns collision point by reference RLAPI bool CheckCollisionPointLine(Vector2 point, Vector2 p1, Vector2 p2, int threshold); // Check if point belongs to line created between two points [p1] and [p2] with defined margin in pixels [threshold] +RLAPI bool CheckCollisionCircleLine(Vector2 center, float radius, Vector2 p1, Vector2 p2); RLAPI Rectangle GetCollisionRec(Rectangle rec1, Rectangle rec2); // Get collision rectangle for two rectangles collision //------------------------------------------------------------------------------------ diff --git a/src/rshapes.c b/src/rshapes.c index 80df64e2d..a786e744f 100644 --- a/src/rshapes.c +++ b/src/rshapes.c @@ -2315,6 +2315,38 @@ bool CheckCollisionPointLine(Vector2 point, Vector2 p1, Vector2 p2, int threshol return collision; } +RLAPI bool CheckCollisionCircleLine(Vector2 center, float radius, Vector2 p1, Vector2 p2) +{ + //test if end points are in circle + bool inside1 = CheckCollisionPointCircle(p1, center, radius); + bool inside2 = CheckCollisionPointCircle(p2, center, radius); + if (inside1 || inside2) return true; + + // get length of line + float dx = p1.x - p2.x; + float dy = p1.y - p2.y; + float length = sqrtf((dx * dx) + (dy * dy)); + + // dot product + float dotProduct = (((center.x - p1.x) * (p2.x - p1.x)) + ((center.y - p1.y) * (p2.y - p1.y))) / (length * length); + + // closest point on line + float closeX = p1.x + (dotProduct * (p2.x - p1.x)); + float closeY = p1.y + (dotProduct * (p2.y - p1.y)); + + bool onSegment = CheckCollisionPointLine((Vector2) { closeX, closeY }, p1, p2, 0); + if (!onSegment) return false; + + //distnce from circle to closest point + + dx = closeX - center.x; + dy = closeY - center.y; + float distance = sqrtf((dx * dx) + (dy * dy)); + + if (distance <= radius) return true; + return false; +} + // Get collision rectangle for two rectangles collision Rectangle GetCollisionRec(Rectangle rec1, Rectangle rec2) {