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