Hi everyone!
I am working on a 2d game where the player is spinning around a planet. While he spins he is supposed to get closer to the planet as longer he spins. Then he can thrust himself out of the gravity of planet 1 and get pulled to planet 2 if he gets the right moment to thrust.
Now my question is how I can get the player spinning around the planet while getting closer to him. Also I have no idea how to manage to get the player tangential out of the gravity of the planet.
I kind of put everything together in an illustration.
As im pretty bad in things like physics in #C I would be very happy if someone who has a bit of knowledge about physics in unity could come up with an idea or code.
There are at least 2 ways of going about this (one performant, the other physically accurate).
- Spheres of Influence (SOI). Each gravitational body (planet) has a sphere (circle in 2d) around it, inside which all orbiting bodies (player/satellite) are pulled towards the center with a constant force. This is the performant approach because you only ever deal with one SOI per object at one time. The caveat here is that you have to take care to ensure SOI’s don’t overlap. Or if they do, you’ll have to assign one precedence over the other. As well, you can have large areas in between gravitational bodies where gravity does not affect your orbiting bodies at all.
- N-body simulation. Each gravitational body is constantly pulling every orbiting body towards the gravitational center with a force proportional to the distance squared between the objects. This means that each satellite is being pulled in N directions at once (hence the name) but in varying amounts. This is how the universe actually works. However, it can be computationally expensive to calculate for large numbers of planets. I’d imagine it would also be a nightmare to try to balance/test/adjust levels so that they work the way you want them to.
Now on to your actual question, the decaying orbits (slowly spiraling in towards the planet) is a side effect of your object slowing down while orbiting (a constant speed would mean a constant orbit). If you go with the SOI approach, you could increase the drag on your object so that it would start slowing down while inside the sphere of influence, simulating atmospheric friction. I wouldn’t imagine you’d need a lot of drag to get the effect you want, but tune to taste. You’d of course need to reset the drag to 0 when you leave the SOI.
As for calculating the direction of gravity at any given point (again assuming SOI implementation) if you take the position of the planet and subtract the position of the satellite, you will get a vector in the direction towards the center of the planet from the satellite’s point of view. You’ll need to calculate that every frame (or physics step, just use FixedUpdate instead of Update) and apply the force in that direction.