39 lines
1.2 KiB
C#
39 lines
1.2 KiB
C#
public struct Vector2
|
|
{
|
|
public float X, Y;
|
|
|
|
public Vector2(float x, float y) { X = x; Y = y; }
|
|
|
|
public float Length => MathF.Sqrt(X * X + Y * Y);
|
|
public float LengthSquared => X * X + Y * Y;
|
|
|
|
// Returns a normalized copy
|
|
public Vector2 Normalized()
|
|
{
|
|
float length = Length;
|
|
if (length > 0.0001f)
|
|
return new Vector2(X / length, Y / length);
|
|
return new Vector2(0, 0);
|
|
}
|
|
|
|
// Normalizes in place
|
|
public void Normalize()
|
|
{
|
|
float length = Length;
|
|
if (length > 0.0001f)
|
|
{
|
|
X /= length;
|
|
Y /= length;
|
|
}
|
|
}
|
|
|
|
// Static normalize
|
|
public static Vector2 Normalize(Vector2 v) => v.Normalized();
|
|
|
|
// Operators
|
|
public static Vector2 operator *(Vector2 v, float s) => new Vector2(v.X * s, v.Y * s);
|
|
public static Vector2 operator *(float s, Vector2 v) => new Vector2(v.X * s, v.Y * s);
|
|
public static Vector2 operator /(Vector2 v, float s) => new Vector2(v.X / s, v.Y / s);
|
|
public static Vector2 operator +(Vector2 a, Vector2 b) => new Vector2(a.X + b.X, a.Y + b.Y);
|
|
public static Vector2 operator -(Vector2 a, Vector2 b) => new Vector2(a.X - b.X, a.Y - b.Y);
|
|
} |