From fa2a9117321b6e6c1d6c04caeb82da088679fea5 Mon Sep 17 00:00:00 2001 From: Sara Date: Sun, 18 Jun 2023 14:39:04 +0200 Subject: [PATCH] added corelib/math/vec.h single header vector math library --- src/corelib/math/vec.h | 43 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/corelib/math/vec.h diff --git a/src/corelib/math/vec.h b/src/corelib/math/vec.h new file mode 100644 index 0000000..07aef07 --- /dev/null +++ b/src/corelib/math/vec.h @@ -0,0 +1,43 @@ +#ifndef _vec_math_h +#define _vec_math_h + +#include "math.h" + +static inline +void clamp_magnitude(float* xx, float* yy, float max_magnitude) { + float x = *xx, y = *yy; + const float m = sqrtf(x*x + y*y); + if(m > max_magnitude) { + x /= m; y /= m; + x *= max_magnitude; y *= max_magnitude; + } + *xx = x; *yy = y; +} + +static inline +void normalize(float* xx, float* yy) { + float x = *xx, y = *yy; + if(x != 0 && y != 0) { + const float m = sqrtf(x*x + y*y); + x /= m; y /= m; + *xx = x; *yy = y; + } +} + +static inline +int move_towards(float* out_x, float* out_y, float x, float y, float tx, float ty, float max_delta) { + const float diff_x = tx - x, diff_y = ty - y; + const float m = sqrtf(diff_x*diff_x + diff_y*diff_y); + const float dir_x = diff_x / m * max_delta, dir_y = diff_y / m * max_delta; + if(dir_x < diff_x && dir_y < diff_y) { + *out_x = x + dir_x; + *out_y = y + dir_y; + return 0; + } else { + *out_x = tx; + *out_y = ty; + return 1; + } +} + +#endif /* _vec_math_h */