Collision_-_CircleRectCollide.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include "raylib.h"
  2. // These are the circlerect collision function. The clamp one is needed for the circlerectcollide.
  3. static bool circlerectcollide(int cx,int cy,int cr, int rx, int ry,int rw,int rh);
  4. static float Clamp(float value, float min, float max);
  5. int main(void)
  6. {
  7. // Initialization
  8. //--------------------------------------------------------------------------------------
  9. const int screenWidth = 800;
  10. const int screenHeight = 450;
  11. InitWindow(screenWidth, screenHeight, "raylib example.");
  12. SetTargetFPS(60); // Set our game to run at 60 frames-per-second
  13. //--------------------------------------------------------------------------------------
  14. // Main game loop
  15. while (!WindowShouldClose()) // Detect window close button or ESC key
  16. {
  17. // Update
  18. //----------------------------------------------------------------------------------
  19. Rectangle r=(Rectangle){GetMouseX(),GetMouseY(),128,64};
  20. Vector2 c=(Vector2){400,200};
  21. float cr=50;
  22. //----------------------------------------------------------------------------------
  23. // Draw
  24. //----------------------------------------------------------------------------------
  25. BeginDrawing();
  26. ClearBackground(RAYWHITE);
  27. DrawRectangle(r.x,r.y,r.width,r.height,BLACK);
  28. DrawCircle(c.x,c.y,cr,BLUE);
  29. if(circlerectcollide(c.x,c.y,cr,r.x,r.y,r.width,r.height)){
  30. DrawText("COLLISION..",20,0,30,RED);
  31. }
  32. EndDrawing();
  33. //----------------------------------------------------------------------------------
  34. }
  35. // De-Initialization
  36. //--------------------------------------------------------------------------------------
  37. CloseWindow(); // Close window and OpenGL context
  38. //--------------------------------------------------------------------------------------
  39. return 0;
  40. }
  41. bool circlerectcollide(int cx,int cy,int cr, int rx, int ry,int rw,int rh){
  42. float closestx = Clamp(cx, rx, rx+rw);
  43. float closesty = Clamp(cy, ry, ry+rh);
  44. float distancex = cx - closestx;
  45. float distancey = cy - closesty;
  46. float distancesquared = (distancex * distancex) + (distancey * distancey);
  47. return distancesquared < (cr * cr);
  48. }
  49. // Clamp float value
  50. float Clamp(float value, float min, float max)
  51. {
  52. const float res = value < min ? min : value;
  53. return res > max ? max : res;
  54. }