From 94d95cb13e76d6cd3ec892a7f0b2bab938a9ba6a Mon Sep 17 00:00:00 2001 From: max-001 Date: Wed, 4 Dec 2024 16:50:23 +0100 Subject: Extended Vector2 --- src/crepe/api/Vector2.h | 24 ++++++++++++++++++++++++ src/crepe/api/Vector2.hpp | 48 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) (limited to 'src/crepe/api') diff --git a/src/crepe/api/Vector2.h b/src/crepe/api/Vector2.h index c278c87..bbcb932 100644 --- a/src/crepe/api/Vector2.h +++ b/src/crepe/api/Vector2.h @@ -66,6 +66,30 @@ struct Vector2 { //! Checks if this vector is not equal to another vector. bool operator!=(const Vector2 & other) const; + + //! Truncates the vector to a maximum length. + void truncate(T max); + + //! Normalizes the vector. + void normalize(); + + //! Returns the length of the vector. + T length() const; + + //! Returns the squared length of the vector. + T length_squared() const; + + //! Returns the dot product of this vector and another vector. + T dot(const Vector2 & other) const; + + //! Returns the distance between this vector and another vector. + T distance(const Vector2 & other) const; + + //! Returns the squared distance between this vector and another vector. + T distance_squared(const Vector2 & other) const; + + //! Returns the perpendicular vector to this vector. + Vector2 perpendicular() const; }; } // namespace crepe diff --git a/src/crepe/api/Vector2.hpp b/src/crepe/api/Vector2.hpp index cad15f8..ff53cb0 100644 --- a/src/crepe/api/Vector2.hpp +++ b/src/crepe/api/Vector2.hpp @@ -1,5 +1,7 @@ #pragma once +#include + #include "Vector2.h" namespace crepe { @@ -115,4 +117,50 @@ bool Vector2::operator!=(const Vector2 & other) const { return !(*this == other); } +template +void Vector2::truncate(T max) { + if (length() > max) { + normalize(); + *this *= max; + } +} + +template +void Vector2::normalize() { + T len = length(); + if (len > 0) { + *this /= len; + } +} + +template +T Vector2::length() const { + return std::sqrt(x * x + y * y); +} + +template +T Vector2::length_squared() const { + return x * x + y * y; +} + +template +T Vector2::dot(const Vector2 & other) const { + return x * other.x + y * other.y; +} + +template +T Vector2::distance(const Vector2 & other) const { + return (*this - other).length(); +} + +template +T Vector2::distance_squared(const Vector2 & other) const { + return (*this - other).length_squared(); +} + +template +Vector2 Vector2::perpendicular() const { + return {-y, x}; +} + } // namespace crepe -- cgit v1.2.3