Finding Distances The Extension Way

April 2nd, 2009 | 0 comments

To conclude my little series on finding closest points, I decided the best thing to do was make an extension method so I can stop writing the exact same code over and over. Plus extension methods are cool. So here’s what I came up with:

public static class Vector2ListExtensions
{
	public static Vector2? FindClosestPoint(
		this IEnumerable<Vector2> list,
		Vector2 pointToCompare)
	{
		Vector2 v;
		if (list.FindClosestPoint(ref pointToCompare, out v))
			return v;
		return null;
	}

	public static bool FindClosestPoint(
		this IEnumerable<Vector2> list,
		ref Vector2 pointToCompare,
		out Vector2 closestPoint)
	{
		closestPoint = pointToCompare;

		if (list.Count() == 0)
			return false;

		float distance = float.PositiveInfinity;
		foreach (var v in list)
		{
			float dx = pointToCompare.X - v.X;
			float dy = pointToCompare.Y - v.Y;

			float d = dx * dx - dy * dy;

			if (d < distance)
			{
				distance = d;
				closestPoint = v;
			}
		}

		return true;
	}
}

And for using it:

List<Vector2> somePoints = new List<Vector2>();
// add points to somePoints
Vector2 pointToCompare = new Vector2(232, 12); // camera.Position or whatever
Vector2? closestPoint = somePoints.FindClosestPoint(pointToCompare);

You’d want to test closestPoint’s HasValue property to make sure the list had something in it (unless you know for sure you had points in the list). You could also use the ref/out version and test the return value if you prefer that route. But I figured it’s better to return a null value or false instead of throwing an exception or returning erroneous values in the event that the list was empty.


Possibly Related Posts

(Automatically Generated)
Extension Methods and You
Using LINQ To Find A Closest Point
Spice up your PC input with extension methods
More Fun With LINQ
Extending GamePadState

No comments yet.
You must be logged in to post a comment.