JacksEscape/Physics_Move.c

84 lines
2.2 KiB
C
Raw Normal View History

2024-02-29 16:51:46 +08:00
2024-02-29 16:59:04 +08:00
#include "Physics_Component.h"
2024-02-29 16:51:46 +08:00
#include "Entity.h"
#include "Types.h"
#include "util/tree.h"
#include <stdlib.h>
static const double EPS = 1e-6;
static inline double dabs(double x) {
return x < 0 ? -x : x;
}
void _physics_MoveX(System_Physics *sys, Entity *e, Duration deltaTime) {
double delta = e->position->velocity.x * duration_Seconds(deltaTime);
2024-03-01 13:29:29 +08:00
Box2 mybox = physics_HitboxAbsolute(e->hitbox);
2024-02-29 16:51:46 +08:00
if (dabs(delta) < EPS)
return;
for (tree_Node *i = tree_FirstNode(sys->hit);
i != NULL;
i = tree_Node_Next(i)) {
2024-03-01 13:29:29 +08:00
Component_Hitbox *tohit_comp = *((Component_Hitbox **)i->data);
Box2 tohit = physics_HitboxAbsolute(tohit_comp);
if (!tohit_comp->fixed)
2024-02-29 16:51:46 +08:00
continue;
2024-03-01 13:29:29 +08:00
if (box2_Intersects(tohit, box2_OffsetX(mybox, delta), NULL)) {
2024-02-29 16:51:46 +08:00
if (delta > 0) {
// Moves right, hits left edge
2024-03-01 13:29:29 +08:00
double maxdelta = tohit.lefttop.x - mybox.lefttop.x - mybox.size.x;
2024-02-29 16:51:46 +08:00
delta = maxdelta - EPS;
} else {
// Moves left, hits right edge
2024-03-01 13:29:29 +08:00
double maxdelta = tohit.lefttop.x - mybox.lefttop.x + tohit.size.x;
2024-02-29 16:51:46 +08:00
delta = maxdelta + EPS;
}
}
if (dabs(delta) < EPS)
break;
}
if (dabs(delta) > EPS)
e->position->position.x += delta;
}
void _physics_MoveY(System_Physics *sys, Entity *e, Duration deltaTime) {
double delta = e->position->velocity.y * duration_Seconds(deltaTime);
2024-03-01 13:29:29 +08:00
Box2 mybox = physics_HitboxAbsolute(e->hitbox);
2024-02-29 16:51:46 +08:00
if (dabs(delta) < EPS)
return;
for (tree_Node *i = tree_FirstNode(sys->hit);
i != NULL;
i = tree_Node_Next(i)) {
2024-03-01 13:29:29 +08:00
Component_Hitbox *tohit_comp = *((Component_Hitbox **)i->data);
Box2 tohit = physics_HitboxAbsolute(tohit_comp);
if (!tohit_comp->fixed)
2024-02-29 16:51:46 +08:00
continue;
2024-03-01 13:29:29 +08:00
if (box2_Intersects(tohit, box2_OffsetY(mybox, delta), NULL)) {
2024-02-29 16:51:46 +08:00
if (delta > 0) {
// Moves down, hits top edge
2024-03-01 13:29:29 +08:00
double maxdelta = tohit.lefttop.y - mybox.lefttop.y - mybox.size.y;
2024-02-29 16:51:46 +08:00
delta = maxdelta - EPS;
} else {
// Moves up, hits bottom edge
2024-03-01 13:29:29 +08:00
double maxdelta = tohit.lefttop.y - mybox.lefttop.y + tohit.size.y;
2024-02-29 16:51:46 +08:00
delta = maxdelta + EPS;
}
}
if (dabs(delta) < EPS)
break;
}
if (dabs(delta) > EPS)
e->position->position.y += delta;
}