From 9e24aa042e9fb9de34f7b445778518fcb67e24aa Mon Sep 17 00:00:00 2001 From: BoredGuy Date: Sun, 15 Mar 2026 17:08:36 +0300 Subject: Some Updates --- src/physics.c | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 src/physics.c (limited to 'src/physics.c') diff --git a/src/physics.c b/src/physics.c new file mode 100644 index 0000000..33065a9 --- /dev/null +++ b/src/physics.c @@ -0,0 +1,78 @@ +#include +#include "game.h" +#include "entity.h" +#include "physics.h" + +extern struct game game; + +static inline bool can_collide(const struct entity* entity) { + return (entity->flags & ENTITY_ACTIVE) && (entity->flags & ENTITY_COLLISION_ACTIVE); +} + +static inline bool aabb(const struct entity* a, const struct entity* b) { + Rectangle acol = get_entity_collider_world(a); + Rectangle bcol = get_entity_collider_world(b); + + bool collision_x = (acol.x <= bcol.x && acol.x + acol.width > bcol.x) || + (bcol.x <= acol.x && bcol.x + bcol.width > acol.x); + bool collision_y = (acol.y <= bcol.y && acol.y + acol.height > bcol.y) || + (bcol.y <= acol.y && bcol.y + bcol.height > acol.y); + + return collision_x && collision_y; +} + +void move_and_collide +( + struct entity* entity, + float delta_time + ) { + entity->position.x += entity->velocity.x * delta_time; + + if (can_collide(entity)) { + for (int i = 0; i < MAX_ENTITY_COUNT; i++) { + struct entity* other = &game.entities[i]; + if (same_entity(entity, other) || !can_collide(other) || !aabb(entity, other)) + continue; + + Rectangle acol = get_entity_collider_world(entity); + Rectangle bcol = get_entity_collider_world(other); + + if (entity->velocity.x > 0) { + entity->position.x = bcol.x - acol.width - entity->collider.x; + + entity_handle_collision(entity, other, Direction_Right); + entity_handle_collision(other, entity, Direction_Left); + } else { + entity->position.x = bcol.x + bcol.width - entity->collider.x; + + entity_handle_collision(entity, other, Direction_Left); + entity_handle_collision(other, entity, Direction_Right); + } + } + } + + entity->position.y += entity->velocity.y * delta_time; + + if (can_collide(entity)) { + for (int i = 0; i < MAX_ENTITY_COUNT; i++) { + struct entity* other = &game.entities[i]; + if (same_entity(other, entity) || !can_collide(other) || !aabb(entity, other)) + continue; + + Rectangle acol = get_entity_collider_world(entity); + Rectangle bcol = get_entity_collider_world(other); + + if (entity->velocity.y > 0) { + entity->position.y = bcol.y - acol.height - entity->collider.y; + + entity_handle_collision(entity, other, Direction_Down); + entity_handle_collision(other, entity, Direction_Up); + } else { + entity->position.y = bcol.y + bcol.height - entity->collider.y; + + entity_handle_collision(entity, other, Direction_Up); + entity_handle_collision(other, entity, Direction_Down); + } + } + } +} -- cgit v1.2.3