Skip to content

Instantly share code, notes, and snippets.

@wldomiciano
Created July 5, 2019 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wldomiciano/b7615dec0b76c1595f8e8c02a1a09a24 to your computer and use it in GitHub Desktop.
Save wldomiciano/b7615dec0b76c1595f8e8c02a1a09a24 to your computer and use it in GitHub Desktop.
// compiles with
// gcc vector.c -Wall -Wextra -Wpedantic `sdl2-config --cflags --libs` -lm
#include <SDL.h>
#include <math.h>
const double PI = 3.14159265358979323846264338327950288;
typedef struct {
double x, y;
} vec2;
double rad2deg(double rad) { return rad * (180 / PI); }
double deg2rad(double deg) { return deg / (180 / PI); }
void vec2_print(vec2 v) { SDL_Log("(%.2f, %.2f)", v.x, v.y); }
vec2 vec2_add(vec2 a, vec2 b) { return (vec2){a.x + b.x, a.y + b.y}; }
float vec2_length(vec2 v) { return sqrtf(v.x * v.x + v.y * v.y); }
vec2 vec2_normalized(const vec2 v) {
double length = vec2_length(v);
return (vec2){v.x / length, v.y / length};
}
double vec2_rotation(const vec2 v) {
double rad = atan2f(v.x, v.y);
return rad2deg(rad);
}
vec2 vec2_rotated(const vec2 v, double angle) {
double rad = deg2rad(angle);
vec2 temp;
temp.x = cos(rad) * v.x - sin(rad) * v.y;
temp.y = sin(rad) * v.x + cos(rad) * v.y;
return temp;
}
int main() {
vec2 p1 = {1, 1};
vec2_print(p1);
SDL_Log("%f", vec2_length(p1));
SDL_Log("%f", vec2_rotation(p1));
SDL_Log(" ");
vec2 p2 = vec2_normalized(vec2_rotated(p1, 90));
vec2_print(p2);
SDL_Log("%f", vec2_length(p2));
SDL_Log("%f", vec2_rotation(p2));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment