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..774275496 100644 --- a/src/rshapes.c +++ b/src/rshapes.c @@ -2315,6 +2315,41 @@ bool CheckCollisionPointLine(Vector2 point, Vector2 p1, Vector2 p2, int threshol return collision; } +RLAPI bool CheckCollisionCircleLine(Vector2 center, float radius, Vector2 p1, Vector2 p2) +{ + // get length of line + float dx = p1.x - p2.x; + float dy = p1.y - p2.y; + float length_sqr = ((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_sqr); + + if (dotProduct > 1.0f) + { + dotProduct = 1.0f; + } + else if (dotProduct < 0.0f) + { + dotProduct = 0.0f; + } + + // closest point on line + float closeX = p1.x - (dotProduct * (dx)); + float closeY = p1.y - (dotProduct * (dy)); + + Vector2 close = { closeX, closeY }; + + //distnce from circle to closest point + + dx = closeX - center.x; + dy = closeY - center.y; + float distance_sqr = ((dx * dx) + (dy * dy)); + + if (distance_sqr <= radius * radius) return true; + return false; +} + // Get collision rectangle for two rectangles collision Rectangle GetCollisionRec(Rectangle rec1, Rectangle rec2) {