What I would like is to loop through each item of a List in ascending order of distance (so the nearest targets are used first).
foreach (ShipCompartment enemyComp in enemy.ListOfCompartments.OrderBy(...))
The problem is that the distance is not a member of the class. Therefore I can't use:
foreach (ShipCompartment enemyComp in enemy.ListOfCompartments
.OrderBy(c => c.Distance))
The code used to calculate distance is:
// Get distance between player and enemy compartments
float distanceToTarget = Vector2.Distance(playerComp.Position,
enemyComp.Position);
How can I incorporate the calculation into OrderBy()? I've looked over here but it only returns the nearest Vector2.
Many thanks for your assistance.
The simple option would be to move the function call to the OrderBy
call, so something like:
foreach (ShipCompartment enemyComp in enemy.ListOfCompartments.OrderBy(c => Vector2.Distance(playerComp.Position, c.Position)))