SG 1 anno fa
parent
commit
758240751a
3 ha cambiato i file con 51 aggiunte e 4 eliminazioni
  1. 2 4
      entity.c
  2. 25 0
      vector.c
  3. 24 0
      vector.h

+ 2 - 4
entity.c

@@ -134,10 +134,8 @@ bool entity_collider_circle_circle(Entity* entity, Entity* other) {
     Vector pos1 = entity_collider_position_get(entity);
     Vector pos2 = entity_collider_position_get(other);
 
-    float dx = pos1.x - pos2.x;
-    float dy = pos1.y - pos2.y;
-    float distance = sqrtf(dx * dx + dy * dy);
-    return distance < entity->collider->circle.radius + other->collider->circle.radius;
+    Vector delta = vector_sub(pos1, pos2);
+    return vector_length(delta) < entity->collider->circle.radius + other->collider->circle.radius;
 }
 
 bool entity_collider_rect_rect(Entity* entity, Entity* other) {

+ 25 - 0
vector.c

@@ -1,4 +1,10 @@
 #include "vector.h"
+#include <math.h>
+
+#undef vector_add
+#undef vector_sub
+#undef vector_mul
+#undef vector_div
 
 Vector vector_add(Vector a, Vector b) {
     return (Vector){.x = a.x + b.x, .y = a.y + b.y};
@@ -30,4 +36,23 @@ Vector vector_mulf(Vector a, float b) {
 
 Vector vector_divf(Vector a, float b) {
     return (Vector){.x = a.x / b, .y = a.y / b};
+}
+
+float vector_length(Vector v) {
+    return sqrtf(v.x * v.x + v.y * v.y);
+}
+
+Vector vector_normalize(Vector v) {
+    float length = vector_length(v);
+    return (Vector){v.x / length, v.y / length};
+}
+
+float vector_dot(Vector a, Vector b) {
+    return a.x * b.x + a.y * b.y;
+}
+
+Vector vector_rand() {
+    float x = (rand() % __INT_MAX__) / (float)__INT_MAX__;
+    float y = (rand() % __INT_MAX__) / (float)__INT_MAX__;
+    return (Vector){x, y};
 }

+ 24 - 0
vector.h

@@ -1,4 +1,5 @@
 #pragma once
+#include <m-core.h>
 
 #ifdef __cplusplus
 extern "C" {
@@ -27,6 +28,29 @@ Vector vector_mulf(Vector a, float b);
 
 Vector vector_divf(Vector a, float b);
 
+float vector_length(Vector v);
+
+Vector vector_normalize(Vector v);
+
+float vector_dot(Vector a, Vector b);
+
+Vector vector_rand();
+
+#define VECTOR_SELECT(func1, func2, a, b) \
+    _Generic(                             \
+        (b),                              \
+        float: func2,                     \
+        const float: func2,               \
+        int: func2,                       \
+        const int: func2,                 \
+        Vector: func1,                    \
+        const Vector: func1)(a, b)
+
+#define vector_add(a, b) VECTOR_SELECT(vector_add, vector_addf, a, b)
+#define vector_sub(a, b) VECTOR_SELECT(vector_sub, vector_subf, a, b)
+#define vector_mul(a, b) VECTOR_SELECT(vector_mul, vector_mulf, a, b)
+#define vector_div(a, b) VECTOR_SELECT(vector_div, vector_divf, a, b)
+
 #ifdef __cplusplus
 }
 #endif