Collision_-_rectsoverlap.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include "raylib.h"
  2. // Our rectsoverlap function. Returns true/false.
  3. static bool rectsoverlap(int x1,int y1,int w1,int h1,int x2,int y2,int w2,int h2);
  4. int main(void)
  5. {
  6. // Initialization
  7. //--------------------------------------------------------------------------------------
  8. const int screenWidth = 800;
  9. const int screenHeight = 450;
  10. InitWindow(screenWidth, screenHeight, "raylib example.");
  11. SetTargetFPS(60); // Set our game to run at 60 frames-per-second
  12. //--------------------------------------------------------------------------------------
  13. // Main game loop
  14. while (!WindowShouldClose()) // Detect window close button or ESC key
  15. {
  16. // Update
  17. //----------------------------------------------------------------------------------
  18. int x1 = GetMouseX();
  19. int y1 = GetMouseY();
  20. int w1 = 64;
  21. int h1 = 64;
  22. int x2 = 200;
  23. int y2 = 200;
  24. int w2 = 100;
  25. int h2 = 100;
  26. //----------------------------------------------------------------------------------
  27. // Draw
  28. //----------------------------------------------------------------------------------
  29. BeginDrawing();
  30. ClearBackground(RAYWHITE);
  31. DrawRectangle(x1,y1,w1,h1,YELLOW);
  32. DrawRectangle(x2,y2,w2,h2,RED);
  33. if(rectsoverlap(x1,y1,w1,h1,x2,y2,w2,h2)){
  34. DrawText("Collision!",0,20,20,DARKGRAY);
  35. }else{
  36. DrawText("No Collision!",0,20,20,DARKGRAY);
  37. }
  38. EndDrawing();
  39. //----------------------------------------------------------------------------------
  40. }
  41. // De-Initialization
  42. //--------------------------------------------------------------------------------------
  43. CloseWindow(); // Close window and OpenGL context
  44. //--------------------------------------------------------------------------------------
  45. return 0;
  46. }
  47. // Rectangles overlap
  48. bool rectsoverlap(int x1,int y1,int w1,int h1,int x2,int y2,int w2,int h2){
  49. if(x1 >= (x2 + w2) || (x1 + w1) <= x2) return false;
  50. if(y1 >= (y2 + h2) || (y1 + h1) <= y2) return false;
  51. return true;
  52. }