- Home /
Distance between 2 objects exteriors?
So I am trying to setup some planets / space ship system, but I am running into an issue. My code checks if the spaceship is in range of the planet it is effected by the gravity. However currently I am calculating the distance by
float dist = Vector3.Distance(planet.transform.position, transform.position);
There is an issue with this, in this screenshot you can see here http://puu.sh/bePps/14841e0600.png the square space ship is effected by the smaller planets gravity but not the larger one. I am assuming this is happening because it is calculating the distance between the spaceship and the center of the planet, not the edge of the planet (like I want)
How can I calculate the distance between the exterior of 2 objects? or at least from the exterior of the planet, I assume it would be something like.
float dist = Vector3.Distance(planet.transform.position+ distanceToExterior, transform.position);
Currently I am making my spheres larger by scaling their transform in the game editor (not sure if that is important)
Answer by AlwaysSunny · Aug 31, 2014 at 07:04 AM
Technically, gravity shouldn't care about the surface of an object; only its mass.
The distance to the exterior of a sphere is its radius. Assuming you're scaling it on all 3 axis equally, that'll be any of the scale components divided by two. (or multiplied by one half, which is cheaper to compute)
(mySphere.localScale.x * 0.5f)
If you wind up using a sphere model whose radius is NOT 0.5, you'll need some extra math. The other possible method involves casting a ray at the surface, which can provide a hit.point and hit.distance, among other things.