#if REAL_T_IS_DOUBLE using real_t = System.Double; #else using real_t = System.Single; #endif using System; using System.Runtime.InteropServices; namespace Godot { /// /// 2-element structure that can be used to represent positions in 2D space or any other pair of numeric values. /// [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Vector2 : IEquatable { /// /// Enumerated index values for the axes. /// Returned by and . /// public enum Axis { X = 0, Y } /// /// The vector's X component. Also accessible by using the index position `[0]`. /// public real_t x; /// /// The vector's Y component. Also accessible by using the index position `[1]`. /// public real_t y; /// /// Access vector components using their index. /// /// `[0]` is equivalent to `.x`, `[1]` is equivalent to `.y`. public real_t this[int index] { get { switch (index) { case 0: return x; case 1: return y; default: throw new IndexOutOfRangeException(); } } set { switch (index) { case 0: x = value; return; case 1: y = value; return; default: throw new IndexOutOfRangeException(); } } } internal void Normalize() { real_t lengthsq = LengthSquared(); if (lengthsq == 0) { x = y = 0f; } else { real_t length = Mathf.Sqrt(lengthsq); x /= length; y /= length; } } /// /// Returns a new vector with all components in absolute values (i.e. positive). /// /// A vector with called on each component. public Vector2 Abs() { return new Vector2(Mathf.Abs(x), Mathf.Abs(y)); } /// /// Returns this vector's angle with respect to the X axis, or (1, 0) vector, in radians. /// /// Equivalent to the result of when /// called with the vector's `y` and `x` as parameters: `Mathf.Atan2(v.y, v.x)`. /// /// The angle of this vector, in radians. public real_t Angle() { return Mathf.Atan2(y, x); } /// /// Returns the angle to the given vector, in radians. /// /// The other vector to compare this vector to. /// The angle between the two vectors, in radians. public real_t AngleTo(Vector2 to) { return Mathf.Atan2(Cross(to), Dot(to)); } /// /// Returns the angle between the line connecting the two points and the X axis, in radians. /// /// The other vector to compare this vector to. /// The angle between the two vectors, in radians. public real_t AngleToPoint(Vector2 to) { return Mathf.Atan2(y - to.y, x - to.x); } /// /// Returns the aspect ratio of this vector, the ratio of `x` to `y`. /// /// The `x` component divided by the `y` component. public real_t Aspect() { return x / y; } /// /// Returns the vector "bounced off" from a plane defined by the given normal. /// /// The normal vector defining the plane to bounce off. Must be normalized. /// The bounced vector. public Vector2 Bounce(Vector2 normal) { return -Reflect(normal); } /// /// Returns a new vector with all components rounded up (towards positive infinity). /// /// A vector with called on each component. public Vector2 Ceil() { return new Vector2(Mathf.Ceil(x), Mathf.Ceil(y)); } /// /// Returns a new vector with all components clamped between the /// components of `min` and `max` using /// . /// /// The vector with minimum allowed values. /// The vector with maximum allowed values. /// The vector with all components clamped. public Vector2 Clamp(Vector2 min, Vector2 max) { return new Vector2 ( Mathf.Clamp(x, min.x, max.x), Mathf.Clamp(y, min.y, max.y) ); } /// /// Returns the cross product of this vector and `b`. /// /// The other vector. /// The cross product value. public real_t Cross(Vector2 b) { return x * b.y - y * b.x; } /// /// Performs a cubic interpolation between vectors `preA`, this vector, `b`, and `postB`, by the given amount `t`. /// /// The destination vector. /// A vector before this vector. /// A vector after `b`. /// A value on the range of 0.0 to 1.0, representing the amount of interpolation. /// The interpolated vector. public Vector2 CubicInterpolate(Vector2 b, Vector2 preA, Vector2 postB, real_t weight) { Vector2 p0 = preA; Vector2 p1 = this; Vector2 p2 = b; Vector2 p3 = postB; real_t t = weight; real_t t2 = t * t; real_t t3 = t2 * t; return 0.5f * (p1 * 2.0f + (-p0 + p2) * t + (2.0f * p0 - 5.0f * p1 + 4 * p2 - p3) * t2 + (-p0 + 3.0f * p1 - 3.0f * p2 + p3) * t3); } /// /// Returns the normalized vector pointing from this vector to `b`. /// /// The other vector to point towards. /// The direction from this vector to `b`. public Vector2 DirectionTo(Vector2 b) { return new Vector2(b.x - x, b.y - y).Normalized(); } /// /// Returns the squared distance between this vector and `to`. /// This method runs faster than , so prefer it if /// you need to compare vectors or need the squared distance for some formula. /// /// The other vector to use. /// The squared distance between the two vectors. public real_t DistanceSquaredTo(Vector2 to) { return (x - to.x) * (x - to.x) + (y - to.y) * (y - to.y); } /// /// Returns the distance between this vector and `to`. /// /// The other vector to use. /// The distance between the two vectors. public real_t DistanceTo(Vector2 to) { return Mathf.Sqrt((x - to.x) * (x - to.x) + (y - to.y) * (y - to.y)); } /// /// Returns the dot product of this vector and `with`. /// /// The other vector to use. /// The dot product of the two vectors. public real_t Dot(Vector2 with) { return x * with.x + y * with.y; } /// /// Returns a new vector with all components rounded down (towards negative infinity). /// /// A vector with called on each component. public Vector2 Floor() { return new Vector2(Mathf.Floor(x), Mathf.Floor(y)); } /// /// Returns the inverse of this vector. This is the same as `new Vector2(1 / v.x, 1 / v.y)`. /// /// The inverse of this vector. public Vector2 Inverse() { return new Vector2(1 / x, 1 / y); } /// /// Returns true if the vector is normalized, and false otherwise. /// /// A bool indicating whether or not the vector is normalized. public bool IsNormalized() { return Mathf.Abs(LengthSquared() - 1.0f) < Mathf.Epsilon; } /// /// Returns the length (magnitude) of this vector. /// /// The length of this vector. public real_t Length() { return Mathf.Sqrt(x * x + y * y); } /// /// Returns the squared length (squared magnitude) of this vector. /// This method runs faster than , so prefer it if /// you need to compare vectors or need the squared length for some formula. /// /// The squared length of this vector. public real_t LengthSquared() { return x * x + y * y; } /// /// Returns the result of the linear interpolation between /// this vector and `to` by amount `weight`. /// /// The destination vector for interpolation. /// A value on the range of 0.0 to 1.0, representing the amount of interpolation. /// The resulting vector of the interpolation. public Vector2 Lerp(Vector2 to, real_t weight) { return new Vector2 ( Mathf.Lerp(x, to.x, weight), Mathf.Lerp(y, to.y, weight) ); } /// /// Returns the result of the linear interpolation between /// this vector and `to` by the vector amount `weight`. /// /// The destination vector for interpolation. /// A vector with components on the range of 0.0 to 1.0, representing the amount of interpolation. /// The resulting vector of the interpolation. public Vector2 Lerp(Vector2 to, Vector2 weight) { return new Vector2 ( Mathf.Lerp(x, to.x, weight.x), Mathf.Lerp(y, to.y, weight.y) ); } /// /// Returns the vector with a maximum length by limiting its length to `length`. /// /// The length to limit to. /// The vector with its length limited. public Vector2 LimitLength(real_t length = 1.0f) { Vector2 v = this; real_t l = Length(); if (l > 0 && length < l) { v /= l; v *= length; } return v; } /// /// Returns the axis of the vector's largest value. See . /// If both components are equal, this method returns . /// /// The index of the largest axis. public Axis MaxAxis() { return x < y ? Axis.Y : Axis.X; } /// /// Returns the axis of the vector's smallest value. See . /// If both components are equal, this method returns . /// /// The index of the smallest axis. public Axis MinAxis() { return x < y ? Axis.X : Axis.Y; } /// /// Moves this vector toward `to` by the fixed `delta` amount. /// /// The vector to move towards. /// The amount to move towards by. /// The resulting vector. public Vector2 MoveToward(Vector2 to, real_t delta) { var v = this; var vd = to - v; var len = vd.Length(); return len <= delta || len < Mathf.Epsilon ? to : v + vd / len * delta; } /// /// Returns the vector scaled to unit length. Equivalent to `v / v.Length()`. /// /// A normalized version of the vector. public Vector2 Normalized() { var v = this; v.Normalize(); return v; } /// /// Returns a vector composed of the of this vector's components and `mod`. /// /// A value representing the divisor of the operation. /// A vector with each component by `mod`. public Vector2 PosMod(real_t mod) { Vector2 v; v.x = Mathf.PosMod(x, mod); v.y = Mathf.PosMod(y, mod); return v; } /// /// Returns a vector composed of the of this vector's components and `modv`'s components. /// /// A vector representing the divisors of the operation. /// A vector with each component by `modv`'s components. public Vector2 PosMod(Vector2 modv) { Vector2 v; v.x = Mathf.PosMod(x, modv.x); v.y = Mathf.PosMod(y, modv.y); return v; } /// /// Returns this vector projected onto another vector `b`. /// /// The vector to project onto. /// The projected vector. public Vector2 Project(Vector2 onNormal) { return onNormal * (Dot(onNormal) / onNormal.LengthSquared()); } /// /// Returns this vector reflected from a plane defined by the given `normal`. /// /// The normal vector defining the plane to reflect from. Must be normalized. /// The reflected vector. public Vector2 Reflect(Vector2 normal) { #if DEBUG if (!normal.IsNormalized()) { throw new ArgumentException("Argument is not normalized", nameof(normal)); } #endif return 2 * Dot(normal) * normal - this; } /// /// Rotates this vector by `phi` radians. /// /// The angle to rotate by, in radians. /// The rotated vector. public Vector2 Rotated(real_t phi) { real_t sine = Mathf.Sin(phi); real_t cosi = Mathf.Cos(phi); return new Vector2( x * cosi - y * sine, x * sine + y * cosi); } /// /// Returns this vector with all components rounded to the nearest integer, /// with halfway cases rounded towards the nearest multiple of two. /// /// The rounded vector. public Vector2 Round() { return new Vector2(Mathf.Round(x), Mathf.Round(y)); } /// /// Returns a vector with each component set to one or negative one, depending /// on the signs of this vector's components, or zero if the component is zero, /// by calling on each component. /// /// A vector with all components as either `1`, `-1`, or `0`. public Vector2 Sign() { Vector2 v; v.x = Mathf.Sign(x); v.y = Mathf.Sign(y); return v; } /// /// Returns the result of the spherical linear interpolation between /// this vector and `to` by amount `weight`. /// /// Note: Both vectors must be normalized. /// /// The destination vector for interpolation. Must be normalized. /// A value on the range of 0.0 to 1.0, representing the amount of interpolation. /// The resulting vector of the interpolation. public Vector2 Slerp(Vector2 to, real_t weight) { #if DEBUG if (!IsNormalized()) { throw new InvalidOperationException("Vector2.Slerp: From vector is not normalized."); } if (!to.IsNormalized()) { throw new InvalidOperationException("Vector2.Slerp: `to` is not normalized."); } #endif return Rotated(AngleTo(to) * weight); } /// /// Returns this vector slid along a plane defined by the given normal. /// /// The normal vector defining the plane to slide on. /// The slid vector. public Vector2 Slide(Vector2 normal) { return this - normal * Dot(normal); } /// /// Returns this vector with each component snapped to the nearest multiple of `step`. /// This can also be used to round to an arbitrary number of decimals. /// /// A vector value representing the step size to snap to. /// The snapped vector. public Vector2 Snapped(Vector2 step) { return new Vector2(Mathf.Snapped(x, step.x), Mathf.Snapped(y, step.y)); } /// /// Returns a perpendicular vector rotated 90 degrees counter-clockwise /// compared to the original, with the same length. /// /// The perpendicular vector. public Vector2 Orthogonal() { return new Vector2(y, -x); } // Constants private static readonly Vector2 _zero = new Vector2(0, 0); private static readonly Vector2 _one = new Vector2(1, 1); private static readonly Vector2 _inf = new Vector2(Mathf.Inf, Mathf.Inf); private static readonly Vector2 _up = new Vector2(0, -1); private static readonly Vector2 _down = new Vector2(0, 1); private static readonly Vector2 _right = new Vector2(1, 0); private static readonly Vector2 _left = new Vector2(-1, 0); /// /// Zero vector, a vector with all components set to `0`. /// /// Equivalent to `new Vector2(0, 0)` public static Vector2 Zero { get { return _zero; } } /// /// One vector, a vector with all components set to `1`. /// /// Equivalent to `new Vector2(1, 1)` public static Vector2 One { get { return _one; } } /// /// Infinity vector, a vector with all components set to `Mathf.Inf`. /// /// Equivalent to `new Vector2(Mathf.Inf, Mathf.Inf)` public static Vector2 Inf { get { return _inf; } } /// /// Up unit vector. Y is down in 2D, so this vector points -Y. /// /// Equivalent to `new Vector2(0, -1)` public static Vector2 Up { get { return _up; } } /// /// Down unit vector. Y is down in 2D, so this vector points +Y. /// /// Equivalent to `new Vector2(0, 1)` public static Vector2 Down { get { return _down; } } /// /// Right unit vector. Represents the direction of right. /// /// Equivalent to `new Vector2(1, 0)` public static Vector2 Right { get { return _right; } } /// /// Left unit vector. Represents the direction of left. /// /// Equivalent to `new Vector2(-1, 0)` public static Vector2 Left { get { return _left; } } /// /// Constructs a new with the given components. /// /// The vector's X component. /// The vector's Y component. public Vector2(real_t x, real_t y) { this.x = x; this.y = y; } /// /// Constructs a new from an existing . /// /// The existing . public Vector2(Vector2 v) { x = v.x; y = v.y; } public static Vector2 operator +(Vector2 left, Vector2 right) { left.x += right.x; left.y += right.y; return left; } public static Vector2 operator -(Vector2 left, Vector2 right) { left.x -= right.x; left.y -= right.y; return left; } public static Vector2 operator -(Vector2 vec) { vec.x = -vec.x; vec.y = -vec.y; return vec; } public static Vector2 operator *(Vector2 vec, real_t scale) { vec.x *= scale; vec.y *= scale; return vec; } public static Vector2 operator *(real_t scale, Vector2 vec) { vec.x *= scale; vec.y *= scale; return vec; } public static Vector2 operator *(Vector2 left, Vector2 right) { left.x *= right.x; left.y *= right.y; return left; } public static Vector2 operator /(Vector2 vec, real_t divisor) { vec.x /= divisor; vec.y /= divisor; return vec; } public static Vector2 operator /(Vector2 vec, Vector2 divisorv) { vec.x /= divisorv.x; vec.y /= divisorv.y; return vec; } public static Vector2 operator %(Vector2 vec, real_t divisor) { vec.x %= divisor; vec.y %= divisor; return vec; } public static Vector2 operator %(Vector2 vec, Vector2 divisorv) { vec.x %= divisorv.x; vec.y %= divisorv.y; return vec; } public static bool operator ==(Vector2 left, Vector2 right) { return left.Equals(right); } public static bool operator !=(Vector2 left, Vector2 right) { return !left.Equals(right); } public static bool operator <(Vector2 left, Vector2 right) { if (left.x == right.x) { return left.y < right.y; } return left.x < right.x; } public static bool operator >(Vector2 left, Vector2 right) { if (left.x == right.x) { return left.y > right.y; } return left.x > right.x; } public static bool operator <=(Vector2 left, Vector2 right) { if (left.x == right.x) { return left.y <= right.y; } return left.x <= right.x; } public static bool operator >=(Vector2 left, Vector2 right) { if (left.x == right.x) { return left.y >= right.y; } return left.x >= right.x; } public override bool Equals(object obj) { if (obj is Vector2) { return Equals((Vector2)obj); } return false; } public bool Equals(Vector2 other) { return x == other.x && y == other.y; } /// /// Returns true if this vector and `other` are approximately equal, by running /// on each component. /// /// The other vector to compare. /// Whether or not the vectors are approximately equal. public bool IsEqualApprox(Vector2 other) { return Mathf.IsEqualApprox(x, other.x) && Mathf.IsEqualApprox(y, other.y); } public override int GetHashCode() { return y.GetHashCode() ^ x.GetHashCode(); } public override string ToString() { return String.Format("({0}, {1})", new object[] { x.ToString(), y.ToString() }); } public string ToString(string format) { return String.Format("({0}, {1})", new object[] { x.ToString(format), y.ToString(format) }); } } }