added corelib/math/vec.h single header vector math library

pull/8/head
Sara 2023-06-18 14:39:04 +02:00
parent ea3beddfec
commit fa2a911732
1 changed files with 43 additions and 0 deletions

43
src/corelib/math/vec.h Normal file
View File

@ -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 */