XNA Find nearest Vector from player
I have a List of vectors and a PlayerVector I just want to know how I can find the nearest Vector to my PlayerVector in my List.
Here are my variables:
List<Vector2> Positions;
Vector2 Player;
The variables are already declared and all, I just need a simple code that will search for the nearest pos开发者_Go百科ition to my player. Isn't there a simple way?
Since you don't need the exact distance (just a relative comparison), you can skip the square-root step in the Pythagorean distance formula:
Vector2? closest = null;
var closestDistance = float.MaxValue;
foreach (var position in Positions) {
var distance = Vector2.DistanceSquared(position, Player);
if (!closest.HasValue || distance < closestDistance) {
closest = position;
closestDistance = distance;
}
}
// closest.Value now contains the closest vector to the player
Create a int called distanceToPlayer, set it to 0.
Create a int called nearestObject set it to 0.
Loop through all the objects with a for loop. It is slightly faster than a foreach loop, and is more useful in this situation.
In the loop:
Get the distance with Vector2.Distance, and check it against distanceToPlayer, if less, then store the index number of the object in nearestObject, and store the new distance in distanceToPlayer.
After the loop is done, you will have the distance in whole pixels, and the index of the item in the list stored. You can access the item using Positions[index].
I'm writing it from memory, because I don't have access to XNA now:
Vector2 nerrest = Positions.Select(vect => new { distance= vect.Distance(Player), vect})
.OrderBy(x => x.distance)
.First().vect;
Little tips: In this solution you probably can use PLINQ to gain little speedup on distance computing.
精彩评论