From 3d1a05d588274536c35f1e667eb65f07e7e0d559 Mon Sep 17 00:00:00 2001 From: mkupiec1 <81627045+mkupiec1@users.noreply.github.com> Date: Wed, 31 Mar 2021 16:50:05 +0200 Subject: [PATCH] [shapes] CheckCollisionPointTriangle (fix), CheckCollisionPointLine (new routine) (#1695) * CheckCollisionPointTriangle * New feature proposal to existing collision detection routines. It checks if point [point] belongs to line created between two points [p1] and [p2] with defined margin in pixels[threshold]. 1693 --- src/shapes.c | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/shapes.c b/src/shapes.c index 89f647d4..789a1f70 100644 --- a/src/shapes.c +++ b/src/shapes.c @@ -1468,7 +1468,7 @@ bool CheckCollisionPointTriangle(Vector2 point, Vector2 p1, Vector2 p2, Vector2 float gamma = 1.0f - alpha - beta; - if ((alpha > 0) && (beta > 0) & (gamma > 0)) collision = true; + if ((alpha > 0) && (beta > 0) && (gamma > 0)) collision = true; return collision; } @@ -1545,6 +1545,26 @@ bool CheckCollisionLines(Vector2 startPos1, Vector2 endPos1, Vector2 startPos2, return true; } +// Check if point belongs to line created between two points [p1] and [p2] with defined margin in pixels [threshold] +bool CheckCollisionPointLine(Vector2 point, Vector2 p1, Vector2 p2, int threshold) +{ + bool collision = false; + float dxc = point.x - p1.x; + float dyc = point.y - p1.y; + float dxl = p2.x - p1.x; + float dyl = p2.y - p1.y; + float cross = dxc*dyl - dyc*dxl; + + if (abs(cross) < threshold*fmaxf(fabsf(dxl), fabsf(dyl))) + { + if (fabsf(dxl) >= fabsf(dyl)) collision = (dxl > 0)? ((p1.x <= point.x) && (point.x <= p2.x)) : ((p2.x <= point.x) && (point.x <= p1.x)); + else + collision = (dyl > 0)? ((p1.y <= point.y) && (point.y <= p2.y)) : ((p2.y <= point.y) && (point.y <= p1.y)); + } + + return collision; +} + // Get collision rectangle for two rectangles collision Rectangle GetCollisionRec(Rectangle rec1, Rectangle rec2) {