|
using System;
namespace Bornander.UI.Physics
{
/// <summary>
/// A representation of a 2D vector.
/// </summary>
public class Vector
{
public static readonly Vector Empty = new Vector();
public Vector()
{
X = 0.0f;
Y = 0.0f;
}
public Vector(float x, float y)
{
this.X = x;
this.Y = y;
}
public Vector(Vector vector)
{
this.X = vector.X;
this.Y = vector.Y;
}
public void Normalize()
{
float length = Length;
if (length > 0.0f)
{
X /= length;
Y /= length;
}
else
{
X = 0.0f;
Y = 0.0f;
}
}
#region Public properties
public float Length
{
get { return (float)Math.Sqrt(X * X + Y * Y); }
}
public float X
{
get;
set;
}
public float Y
{
get;
set;
}
#endregion
#region Public static methods/operators
public static Vector Normalize(Vector vector)
{
float length = vector.Length;
if (length > 0.0f)
return new Vector(vector.X / length, vector.Y / length);
else
return Vector.Empty;
}
public static Vector operator +(Vector lhs, Vector rhs)
{
return new Vector(lhs.X + rhs.X, lhs.Y + rhs.Y);
}
public static Vector operator -(Vector lhs, Vector rhs)
{
return new Vector(lhs.X - rhs.X, lhs.Y - rhs.Y);
}
public static Vector operator *(Vector lhs, float rhs)
{
return new Vector(lhs.X * rhs, lhs.Y * rhs);
}
public static float Dot(Vector lhs, Vector rhs)
{
return lhs.X * rhs.X + lhs.Y * rhs.Y;
}
public static float DistanceBetween(Vector lhs, Vector rhs)
{
return (lhs - rhs).Length;
}
public static explicit operator Vector(System.Drawing.Point point)
{
return new Vector(point.X, point.Y);
}
public static explicit operator System.Drawing.Point(Vector vector)
{
return new System.Drawing.Point((int)vector.X, (int)vector.Y);
}
#endregion
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
Article videos
Oakmead Apps Android Games
21 Feb 2014: Best VB.NET Article of January 2014 - Second Prize
18 Oct 2013: Best VB.NET article of September 2013
23 Jun 2012: Best C++ article of May 2012
20 Apr 2012: Best VB.NET article of March 2012
22 Feb 2010: Best overall article of January 2010
22 Feb 2010: Best C# article of January 2010