diff --git a/olcUTIL_Geometry2D.h b/olcUTIL_Geometry2D.h index cedf02a..fe578fa 100644 --- a/olcUTIL_Geometry2D.h +++ b/olcUTIL_Geometry2D.h @@ -338,6 +338,12 @@ namespace olc return (*this) - 2.0 * (this->dot(n) * n); } + inline constexpr auto distance(const v_2d& p) const + { + // Find the distance between two points + return std::sqrt(std::pow(this->x - p.x, 2) + std::pow(this->y - p.y, 2)); + } + // Allow 'casting' from other v_2d types template inline constexpr operator v_2d() const @@ -1168,8 +1174,66 @@ namespace olc::utils::geom2d } + // ========================================================================================================================= + // constrain(shape, point) =================================================================================================== + template + inline olc::v_2d constrain(const line& l, const olc::v_2d& p) + { + if (contains(l, p)) + { + // The point is already on the line, no need to constrain + return p; + } + else { + // Constrain the point to the closest position on the line + return closest(l, p); + } + } + template + inline olc::v_2d constrain(const circle& c, const olc::v_2d& p) + { + if (contains(c, p)) + { + // The point is already inside the circle, no need to constrain + return p; + } + else { + // Constrain the point to the closest position inside the circle + return closest(c, p); + } + } + + template + inline olc::v_2d constrain(const rect& r, const olc::v_2d& p) + { + if (contains(r, p)) + { + // The point is already inside the rect, no need to constrain + return p; + } + else { + // Constrain the point to the closest position inside the trct + return closest(r, p); + } + + } + + template + inline olc::v_2d constrain(const triangle& t, const olc::v_2d& p) + { + if (contains(t, p)) + { + // The point is already inside the triangle, no need to constrain + return p; + } + else { + // Constrain the point to the closest position inside the triangle + return closest(t, p); + } + + }