From 56a4aa9d393bb418708511385f2a7d4838917767 Mon Sep 17 00:00:00 2001 From: herbglitch Date: Mon, 26 Jun 2023 01:27:30 -0600 Subject: [PATCH] collide and slide function for FRect --- include/arc/math/rectangle.h | 16 ++++++++++++++++ src/math/rectangle.c | 27 +++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/include/arc/math/rectangle.h b/include/arc/math/rectangle.h index 183362b..7427579 100644 --- a/include/arc/math/rectangle.h +++ b/include/arc/math/rectangle.h @@ -3,6 +3,7 @@ #include #include "point.h" +#include "vector2.h" #ifdef __cplusplus extern "C" { @@ -118,6 +119,21 @@ int32_t ARC_FRect_IntersectsPoint(ARC_FRect *rect, ARC_Point *point); */ int32_t ARC_Rect_LineIntersects(ARC_Rect *rect, int32_t *x1, int32_t *y1, int32_t *x2, int32_t *y2); +/** + * @brief checks for a ARC_Rect on ARC_Rect collision and slides on collision + * + * @note need to update this documenation to word it better + * + * @param rect ARC_Rect that might collide with the wall + * @param velocity the ammount ARC_Rect will move + * @param wall ARC_Rect that might have collision with rect + * + * @note velocity is updated based on colliding, + * rect's values are not changed, + * velocity should be applied after + */ +void ARC_FRect_CollideAndSlide(ARC_FRect *rect, ARC_Vector2 *velocity, ARC_FRect *wall); + #ifdef __cplusplus } #endif diff --git a/src/math/rectangle.c b/src/math/rectangle.c index 42de8c2..ce1a3d4 100644 --- a/src/math/rectangle.c +++ b/src/math/rectangle.c @@ -69,3 +69,30 @@ int32_t ARC_Rect_LineIntersects(ARC_Rect *rect, int32_t *x1, int32_t *y1, int32_ return 1; } +//TODO: position 1px away from colliding, so if velocity is greater than 2px it doesn't have weird gap spacing +// might need to check diagnals as well, this is a rudamentry implementation +void ARC_FRect_CollideAndSlide(ARC_FRect *rect, ARC_Vector2 *velocity, ARC_FRect *wall){ + ARC_FRect nextRectPosition = { + .x = rect->x + velocity->x, + .y = rect->y + velocity->y, + .w = rect->w, + .h = rect->h + }; + + //there is no collision, return + if(!ARC_FRect_Intersects(&nextRectPosition, wall)){ + return; + } + + nextRectPosition.x = rect->x + velocity->x; + nextRectPosition.y = rect->y; + if(ARC_FRect_Intersects(&nextRectPosition, wall)){ + velocity->x = 0; + } + + nextRectPosition.x = rect->x; + nextRectPosition.y = rect->y + velocity->y; + if(ARC_FRect_Intersects(&nextRectPosition, wall)){ + velocity->y = 0; + } +} \ No newline at end of file