|
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.
(comments are locked)
|
|
you could find a nearest planet by searching for smallest distance between planets and player. C# code Nice mix of C# and JS ;)
May 28 '11 at 11:58 AM
Bunny83
oh thanks :) edited the mix part anyway it doesn't need squareroot when comparing the distances.
May 28 '11 at 12:02 PM
iggy
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.
May 28 '11 at 12:07 PM
Joshua
nearestDistance is reseted to MaxValue. i didn't understand how would square rooting it make it faster? what am i missing?
May 28 '11 at 12:10 PM
iggy
http://unity3d.com/support/documentation/ScriptReference/Vector3-sqrMagnitude.html "Calculating the squared magnitude instead 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. ;)
May 28 '11 at 12:21 PM
Joshua
(comments are locked)
|
|
oh... that's a much more elegant solution than I had attempted. Thanks a lot everyone!
(comments are locked)
|

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.