# Find nearest object using Physics.OverlapSphere

 0 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. more ▼ asked May 27 '11 at 07:03 PM burkleypatterson 1 ● 1 ● 1 ● 1 So you're using OverlapSphere.. centered on the player? With a radius equal to the distance to the farthest planet? How many planets? May 27 '11 at 07:06 PM flaviusxvii yes. the sphere is centered on the player and the radius is an arbitrary number I chose because I knew would include all the planets. The game play shouldn't require more than ten or so planets to be active at a time. to clarify, I have my normal gravity script working. It just loops over all the sphere collisions with the planets and applies a corresponding force to the player. I'm having trouble modifying this to only apply force from the nearest planet. May 27 '11 at 07:23 PM burkleypatterson add new comment (comments are locked) 10|3000 characters needed characters left ▼ Viewable by all users

 0 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
 0 oh... that's a much more elegant solution than I had attempted. Thanks a lot everyone! more ▼ answered May 28 '11 at 01:35 PM burkleypatterson 1 ● 1 ● 1 ● 1 add new comment (comments are locked) 10|3000 characters needed characters left ▼ Viewable by all users

By Email:

Topics:

x1089
x458
x197
x18

asked: May 27 '11 at 07:03 PM

Seen: 2075 times

Last Updated: May 28 '11 at 01:35 PM