help ordering array for planetary gravity
Planets = GameObject.FindGameObjectsWithTag ("Planet"); Planets = Planets.OrderBy(Enem => Vector2.Distance(transform.position,Enem.transform.position) - Enem.transform.localScale.x/2).ToArray(); closestPlanet= Planets[0];
i'm stumped on this part of my code because it's pourpose is to move an object to the closest planet, but if one planet is very big and a small planet is next to it, while the player is walking on the bigger planet, the smaller planet pulls the player towards it because the player was closer to the center of the smaller planet than to the bigger planet it was on. how do i make it so it orders the array by how close it is to the surface and not to the center?
Answer by Asgardr · Nov 08, 2015 at 11:41 AM
If your planets have SphereCollider, you can use SphereCollider.radius and substract it from the distance between you and the center of a planet. As following:
Planets = GameObject.FindGameObjectsWithTag ("Planet");
Planets = Planets.OrderBy(
Enem => Vector2.Distance(transform.position,Enem.transform.position)
- Enem.GetComponent<SphereCollider>().radius
).ToArray();
closestPlanet= Planets[0];
As a sidenote, please don't do this every frame. GetComponent could seriously slow down your update loop. I recommend caching that in some way. Also, some other optimizations could be replacing your Distance with a squared Distance
(obj1.position - obj2.position).sqrMagnitude
This means you don't have to calculate the root of the sqrMagnitude every frame (slow).
that didn't work, i was wontering if there is a solution maybe using linecast or raycast 2D. finding the distance from transform.position to hit point.
What didn't work? If your planets have sphere colliders, it should work. Is there something else that could cause it?