From 1a620bd5faebd83015182ea032f40936a9916af6 Mon Sep 17 00:00:00 2001 From: Ferenc Arn Date: Fri, 31 Mar 2017 10:25:09 -0500 Subject: Made slide and reflect active verbs acting on itself in Vector2 and Vector3. This is in alignment with other functions in vector classes. Also added checks for normalization, fixed the sign of reflect (which now corresponds to reflection along a plane mathematically), added bounce method and updated docs. Fixes #8201. --- core/math/math_2d.cpp | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) (limited to 'core/math/math_2d.cpp') diff --git a/core/math/math_2d.cpp b/core/math/math_2d.cpp index 8f942c423f..77cff6a052 100644 --- a/core/math/math_2d.cpp +++ b/core/math/math_2d.cpp @@ -61,6 +61,10 @@ Vector2 Vector2::normalized() const { return v; } +bool Vector2::is_normalized() const { + return Math::isequal_approx(length(), (real_t)1.0); +} + real_t Vector2::distance_to(const Vector2 &p_vector2) const { return Math::sqrt((x - p_vector2.x) * (x - p_vector2.x) + (y - p_vector2.y) * (y - p_vector2.y)); @@ -274,13 +278,23 @@ Vector2 Vector2::cubic_interpolate(const Vector2 &p_b, const Vector2 &p_pre_a, c */ } -Vector2 Vector2::slide(const Vector2 &p_vec) const { +// slide returns the component of the vector along the given plane, specified by its normal vector. +Vector2 Vector2::slide(const Vector2 &p_n) const { +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_V(p_n.is_normalized() == false, Vector2()); +#endif + return *this - p_n * this->dot(p_n); +} - return p_vec - *this * this->dot(p_vec); +Vector2 Vector2::bounce(const Vector2 &p_n) const { + return -reflect(p_n); } -Vector2 Vector2::reflect(const Vector2 &p_vec) const { - return p_vec - *this * this->dot(p_vec) * 2.0; +Vector2 Vector2::reflect(const Vector2 &p_n) const { +#ifdef DEBUG_ENABLED + ERR_FAIL_COND_V(p_n.is_normalized() == false, Vector2()); +#endif + return 2.0 * p_n * this->dot(p_n) - *this; } bool Rect2::intersects_segment(const Point2 &p_from, const Point2 &p_to, Point2 *r_pos, Point2 *r_normal) const { -- cgit v1.2.3