Skip to content

Instantly share code, notes, and snippets.

@Beyarz
Created June 8, 2024 12:42
Show Gist options
  • Save Beyarz/1bef19499f7324b1f33383a84e0d77e7 to your computer and use it in GitHub Desktop.
Save Beyarz/1bef19499f7324b1f33383a84e0d77e7 to your computer and use it in GitHub Desktop.
Check collision between a circle and a rectangle
#include <math.h>
typedef float f32;
typedef struct Vector2
{
f32 x, y;
} Vector2;
typedef SDL_FRect RectangleF;
typedef struct Circle
{
Vector2 pos;
f32 radius;
} Circle;
bool check_collision_circle_rect(Circle* car_hitbox, RectangleF tile)
{
// Calculate the closest point on the rectangle to the center of the circle
f32 closest_x = fmaxf(tile.x, fminf(car_hitbox->pos.x, tile.x + tile.w));
f32 closest_y = fmaxf(tile.y, fminf(car_hitbox->pos.y, tile.y + tile.h));
// Calculate the distance between the closest point on the rectangle and the center of the circle
f32 distance_x = car_hitbox->pos.x - closest_x;
f32 distance_y = car_hitbox->pos.y - closest_y;
// Calculate the squared distance between the closest point and the center of the circle
f32 distance_squared = powf(distance_x, 2) + powf(distance_y, 2);
// If the squared distance is less than or equal to the squared radius, there is a collision
if (distance_squared <= powf(car_hitbox->radius, 2))
return true;
// If the circle's center is outside the rectangle, check if the circle intersects with the rectangle's edges
if (car_hitbox->pos.x < tile.x)
distance_x = tile.x - car_hitbox->pos.x;
else if (car_hitbox->pos.x > tile.x + tile.w)
distance_x = car_hitbox->pos.x - (tile.x + tile.w);
else
distance_x = 0;
if (car_hitbox->pos.y < tile.y)
distance_y = tile.y - car_hitbox->pos.y;
else if (car_hitbox->pos.y > tile.y + tile.h)
distance_y = car_hitbox->pos.y - (tile.y + tile.h);
else
distance_y = 0;
distance_squared = powf(distance_x, 2) + powf(distance_y, 2);
// If the squared distance is less than or equal to the squared radius, there is a collision
return distance_squared <= powf(car_hitbox->radius, 2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment