using System; using Microsoft.Xna.Framework; namespace Barotrauma.Extensions { public static class VectorExtensions { /// /// Unity's Angle implementation without the conversion to degrees. /// Returns the angle in radians between two vectors. /// 0 - Pi. /// public static float Angle(this Vector2 from, Vector2 to) { return (float)Math.Acos(MathHelper.Clamp(Vector2.Dot(Vector2.Normalize(from), Vector2.Normalize(to)), -1f, 1f)); } /// /// Creates a forward pointing vector based on the rotation (in radians). /// public static Vector2 Forward(float radians, float length = 1) { return new Vector2((float)Math.Cos(radians), (float)Math.Sin(radians)) * length; } /// /// Creates a backward pointing vector based on the rotation (in radians). /// public static Vector2 Backward(float radians, float length = 1) { return -Forward(radians, length); } /// /// Creates a forward pointing vector based on the rotation (in radians). TODO: remove when the implications have been neutralized /// public static Vector2 ForwardFlipped(float radians, float length = 1) { return new Vector2((float)Math.Sin(radians), (float)Math.Cos(radians)) * length; } /// /// Creates a backward pointing vector based on the rotation (in radians). TODO: remove when the implications have been neutralized /// public static Vector2 BackwardFlipped(float radians, float length = 1) { return -ForwardFlipped(radians, length); } /// /// Creates a normalized perpendicular vector to the right from a forward vector. /// public static Vector2 Right(this Vector2 forward) { var normV = Vector2.Normalize(forward); return new Vector2(normV.Y, -normV.X); } /// /// Creates a normalized perpendicular vector to the left from a forward vector. /// public static Vector2 Left(this Vector2 forward) { return -forward.Right(); } /// /// Transforms a vector relative to the given up vector. /// public static Vector2 TransformVector(this Vector2 v, Vector2 up) { return (up * v.Y) + (up.Right() * v.X); } /// /// Flips the x and y components. /// public static Vector2 Flip(this Vector2 v) => new Vector2(v.Y, v.X); /// /// Returns the sum of the x and y components. /// public static float Combine(this Vector2 v) => v.X + v.Y; public static Vector2 Clamp(this Vector2 v, Vector2 min, Vector2 max) { return Vector2.Clamp(v, min, max); } public static bool NearlyEquals(this Vector2 v, Vector2 other) { return MathUtils.NearlyEqual(v.X, other.X) && MathUtils.NearlyEqual(v.Y, other.Y); } } }