- Home /
Find nearest object using Physics.OverlapSphere
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.
So you're using OverlapSphere.. centered on the player? With a radius equal to the distance to the farthest planet? How many planets?
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.
Answer by iggy · May 28, 2011 at 10:50 AM
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;
}
}
Nice mix of C# and JS ;)
After converting your script to one language it should work. But it's better to use sqr$$anonymous$$agnitude ins$$anonymous$$d of magnitude/Vector3.Distance. Vector3.Distance calculates the correct distance but it needs a squareroot. If you just want to compare distances you can use the squared distance.
foreach(GameObject planet in planets) {
distance = (player.transform.position - planet.transform.position).sqr$$anonymous$$agnitude;
[...]
oh thanks :) edited the mix part
anyway it doesn't need squareroot when comparing the distances.
Doesn't 'need' it, but would make it faster. Also, if you use this more then once you'll have to reset nearerDistance to zero.
nearestDistance is reseted to $$anonymous$$axValue.
i didn't understand how would square rooting it make it faster? what am i missing?
http://unity3d.com/support/documentation/ScriptReference/Vector3-sqr$$anonymous$$agnitude.html "Calculating the squared magnitude ins$$anonymous$$d of the magnitude is much faster. Often if you are comparing magnitudes of two vectors you can just compare their squared magnitudes." Since you don't know the ammount planet in planets will return, this might make quite a bit difference. ;)
Answer by burkleypatterson · May 28, 2011 at 01:35 PM
oh... that's a much more elegant solution than I had attempted. Thanks a lot everyone!