I am making a game that uses planetary gravity and I want the player to be able to use a kind of “augmented gravity.” That is, I only want gravity from the nearest planet to act on the player. To do this I want to make a function that sorts through the objects returned by Physics.OverlapSphere for the nearest one so my gravity script only applies gravity from the nearest planet.
Does anyone have such a sorting function I can use? I’ve tried doing it myself, but I’m having some trouble with using arrays.
you could find a nearest planet by searching for smallest distance between planets and player.
C# code
GameObject nearestPlanet;
float nearestDistance=float.MaxValue;
float distance;
foreach(GameObject planet in planets) {
distance = (player.transform.position, planet.transform.position).sqrMagnitude;;
if (distance<nearestDistance) {
nearestDistance=distance;
nearestPlanet=planet;
}
}
oh… that’s a much more elegant solution than I had attempted. Thanks a lot everyone!