From 0c7cbeaa6c998994112047b39889bc96b9629fc3 Mon Sep 17 00:00:00 2001 From: Sara Date: Sun, 26 Jan 2025 21:13:25 +0100 Subject: [PATCH] feat: added reflect --- src/core/math/vector.cpp | 5 +++++ src/core/math/vector.hpp | 2 ++ 2 files changed, 7 insertions(+) diff --git a/src/core/math/vector.cpp b/src/core/math/vector.cpp index fbd4c2f..bd4e1b0 100644 --- a/src/core/math/vector.cpp +++ b/src/core/math/vector.cpp @@ -39,6 +39,11 @@ Vecf Vecf::move_towards(Vecf const &from, Vecf const &to, float delta) { return Vecf::lerp(from, to, delta / Vecf::distance(from, to)); } +Vecf Vecf::reflect(Vecf const &in, Vecf const &normal) { + Vecf const midpoint{normal * Vecf::dot(normal, in)}; + return (midpoint - in) + midpoint; +} + float Vecf::magnitude() const { return std::sqrt(this->x * this->x + this->y * this->y); } diff --git a/src/core/math/vector.hpp b/src/core/math/vector.hpp index 13f5db6..eef8e1c 100644 --- a/src/core/math/vector.hpp +++ b/src/core/math/vector.hpp @@ -22,6 +22,8 @@ struct Vecf { static Vecf lerp(Vecf const &from, Vecf const &to, float t); //! move towards a point by a set unit distance static Vecf move_towards(Vecf const &from, Vecf const &to, float delta); + //! calculate the outgoing velocity of an object reflecting against a surface + static Vecf reflect(Vecf const &in, Vecf const &normal); //! magnitude (a.k.a length or absolute) of this vector float magnitude() const; //! square of the magnitude, use for comparing lengths of vectors efficiently