diff --git a/src/core/math.cpp b/src/core/math.cpp index c9a25b2..f805e69 100644 --- a/src/core/math.cpp +++ b/src/core/math.cpp @@ -99,4 +99,19 @@ float Vector::mag() const return sqrt(x * x + y * y); } +Vector Vector::normalize() const +{ + auto magnitude = mag(); + if (magnitude != 0.0f) + { + auto norm_x = x / magnitude; + auto norm_y = y / magnitude; + return Vector(norm_x, norm_y); + } + else + { + return Vector(0.0f, 0.0f); + } +} + } // namespace core diff --git a/src/core/math.hpp b/src/core/math.hpp index e864228..75c2438 100644 --- a/src/core/math.hpp +++ b/src/core/math.hpp @@ -39,6 +39,8 @@ struct Vector float mag() const; + Vector normalize() const; + float x; float y; }; diff --git a/test/core/math.cpp b/test/core/math.cpp index edd9151..645cb44 100644 --- a/test/core/math.cpp +++ b/test/core/math.cpp @@ -156,3 +156,29 @@ TEST(math_vector_mag, mag_negative_test) ASSERT_FLOAT_EQ(25.0f, result); } +TEST(math_vector_normalize, normalize_zero_test) +{ + auto a = core::Vector(0.0f, 0.0f); + auto result = a.normalize(); + ASSERT_FLOAT_EQ(0.0f, result.mag()); + ASSERT_FLOAT_EQ(0.0f, result.x); + ASSERT_FLOAT_EQ(0.0f, result.y); +} + +TEST(math_vector_normalize, normalize_positive_test) +{ + auto a = core::Vector(8.0f, 15.0f); + auto result = a.normalize(); + ASSERT_FLOAT_EQ(1.0f, result.mag()); + ASSERT_FLOAT_EQ(8.0f / 17.f, result.x); + ASSERT_FLOAT_EQ(15.0f / 17.f, result.y); +} + +TEST(math_vector_normalize, normalize_negative_test) +{ + auto a = core::Vector(-7.0f, -24.0f); + auto result = a.normalize(); + ASSERT_FLOAT_EQ(1.0f, result.mag()); + ASSERT_FLOAT_EQ(-7.0f / 25.f, result.x); + ASSERT_FLOAT_EQ(-24.0f / 25.f, result.y); +}