Implement collision detection

This commit is contained in:
Camden Dixie O'Brien
2025-10-14 16:18:14 +01:00
parent 85984a0a07
commit d3b1b3f926

27
game.c
View File

@@ -36,6 +36,7 @@
#define MAX_SHAPES 256U
#define MAX_ENTITIES 128U
#define MAX_SHAPES_PER_ENTITY 2
#define MAX_COLLISIONS 128U
#define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))
@@ -65,6 +66,9 @@ typedef struct {
uint8_t flags;
} shape_t;
typedef struct {
unsigned entities[2];
} collision_t;
static const vec2_t ship_verts[] = {
{ 0.0, 0.11 },
@@ -236,6 +240,25 @@ static void ship_update()
fire->verts[0].y = FIRE_MEAN + FIRE_JITTER * rng_plusminus();
}
static unsigned check_collisions(collision_t *out)
{
unsigned count = 0;
for (unsigned i = 0; i < entity_count; ++i) {
const entity_t *a = entities + i;
for (unsigned j = i + 1; j < entity_count; ++j) {
const entity_t *b = entities + j;
const float r = vec2_len(vec2_sub(b->pos, a->pos));
if (r <= a->collision_radius + b->collision_radius) {
assert(count < MAX_COLLISIONS);
collision_t *col = out + count++;
col->entities[0] = i;
col->entities[1] = j;
}
}
}
return count;
}
void game_init(float _aspect)
{
input_on_shoot(shoot);
@@ -267,6 +290,7 @@ void game_init(float _aspect)
void game_update()
{
ship_update();
for (unsigned i = 0; i < entity_count; ++i) {
@@ -294,6 +318,9 @@ void game_update()
transforms[i]
= mat3_mul_mat3(mat3_translation(e->pos), mat2_extend(e->dir));
}
static collision_t collisions[MAX_COLLISIONS];
const unsigned ncols = check_collisions(collisions);
}
void game_draw()