Add ClampMagnitude

This commit is contained in:
Pascal Serrarens 2024-04-17 15:20:12 +02:00
parent d01c5d9de5
commit bfa1123994
2 changed files with 214 additions and 203 deletions

View File

@ -63,6 +63,15 @@ Vector2 Vector2::normalized() const {
return result; return result;
} }
Vector2 Vector2::ClampMagnitude(const Vector2 &v, float magnitude) {
float length = Vector2::Magnitude(v);
Vector2 r = v;
if (length > magnitude)
r = v / (length * magnitude);
return r;
}
Vector2 Vector2::operator-(const Vector2 &v2) const { Vector2 Vector2::operator-(const Vector2 &v2) const {
return Vector2(this->x - v2.x, this->y - v2.y); return Vector2(this->x - v2.x, this->y - v2.y);
} }
@ -81,7 +90,7 @@ Vector2 Vector2::operator*(float f) const {
return Vector2(this->x * f, this->y * f); return Vector2(this->x * f, this->y * f);
} }
Vector2 Vector2::operator/(const float &d) { Vector2 Vector2::operator/(const float &d) const {
return Vector2(this->x / d, this->y / d); return Vector2(this->x / d, this->y / d);
} }

View File

@ -121,6 +121,8 @@ public:
/// <returns>The vector with length 1</returns> /// <returns>The vector with length 1</returns>
Vector2 normalized() const; Vector2 normalized() const;
static Vector2 ClampMagnitude(const Vector2 &v, float magnitude);
/// <summary> /// <summary>
/// Negate the vector /// Negate the vector
/// </summary> /// </summary>
@ -163,7 +165,7 @@ public:
/// <param name="factor">The scaling factor</param> /// <param name="factor">The scaling factor</param>
/// <returns>The scaled vector</returns> /// <returns>The scaled vector</returns>
/// Each componet of the vector will be divided by the same factor. /// Each componet of the vector will be divided by the same factor.
Vector2 operator/(const float& factor); Vector2 operator/(const float &factor) const;
/// <summary> /// <summary>
/// The dot product of two vectors /// The dot product of two vectors