summary refs log tree commit diff
path: root/src/Math/Ray.hpp
diff options
context:
space:
mode:
authorMel <einebeere@gmail.com>2023-11-21 02:28:00 +0100
committerMel <einebeere@gmail.com>2023-11-21 02:28:00 +0100
commitca8b16620ec207f2b32edd1f5d46f7b0bfb0a14c (patch)
tree02746322c4229431e36b892f11f07a81ce21e439 /src/Math/Ray.hpp
parent272e6a63df7369e5afcb16c5a6c14f7dd6a75893 (diff)
downloadmeowcraft-ca8b16620ec207f2b32edd1f5d46f7b0bfb0a14c.tar.zst
meowcraft-ca8b16620ec207f2b32edd1f5d46f7b0bfb0a14c.zip
Clumsy non-swept AABB collision system for Player
Diffstat (limited to 'src/Math/Ray.hpp')
-rw-r--r--src/Math/Ray.hpp33
1 files changed, 33 insertions, 0 deletions
diff --git a/src/Math/Ray.hpp b/src/Math/Ray.hpp
new file mode 100644
index 0000000..f83a2b5
--- /dev/null
+++ b/src/Math/Ray.hpp
@@ -0,0 +1,33 @@
+#pragma once
+
+#include "../Common/Lambda.hpp"
+#include "AABB.hpp"
+#include "Vector.hpp"
+
+struct Ray {
+    struct RaycastResult {
+        Bool hit = false;
+        Vec3 point;
+        Vec3 normal;
+    };
+
+    // https://gdbooks.gitbooks.io/3dcollisions/content/Chapter3/raycast_aabb.html
+    RaycastResult cast(AABB box) const {
+        Vec3 t_from = (box.min - origin) / direction;
+        Vec3 t_to = (box.max - origin) / direction;
+
+        Real t_min = t_from.zip(t_to, LAMBDA(std::min, 2)).reduce(LAMBDA(std::max, 2));
+        Real t_max = t_from.zip(t_to, LAMBDA(std::max, 2)).reduce(LAMBDA(std::min, 2));
+
+        if (t_max < 0 || t_min > t_max) return {};
+
+        return {
+            .hit = true,
+            .point = origin + direction * t_min,
+            .normal = t_from.zip(t_to, [](auto a, auto b) { return a < b ? -1.0 : 1.0; })
+        };
+    }
+
+    Vec3 origin;
+    Vec3 direction;
+};