I'm writing a mod for a game that models orbital physics (Kerbal Space Program, or KSP). I'm attempting to model the effects of thrust on spacecraft in certain states where the game only models them as a Keplerian orbit (The ship is 'on rails'), and I'm having some difficulty with numerical stability - even if I don't have any thrust applied I end up constantly increasing eccentricity for the orbit.
In the 'on rails' state, a spacecraft in the game follows a Keplerian orbit exactly. The orbit is calculated when the spacecraft is put on rails, and then when it goes off rails the game calculates the expected position and velocity at the current time and sets up the spacecraft to do normal Newtonian things from there.
At the moment, all my code does is take the calculated position and velocity of the spacecraft at the current time (using the game's own code) and then call a function already present in the game to calculate a Keplerian orbit for an object with that position and velocity around the currently-dominant body - that is, it should be a no-op. I'm actually seeing the orbit's eccentricity drift rapidly, certainly quickly enough that this won't work for gameplay purposes. This code is being called every physics timestep in the game, which is rather often - something like 50 times a second - so I suspect what I'm seeing is that the code in the game for calculating position and velocity from orbit and vice-versa isn't stable. I've verified that in actual gameplay taking a vessel off rails and then putting it back on rails can cause observable orbital differences, and I've confirmed that the calculated position/velocity of the craft change after I recalculate the orbit. Relative error in position is about $10^{-8}$, relative error in velocity is about $10^{-2}$.
I'm not sure what the best solution is here, and I only have very limited experience with numerical computation. I'd like to know what a good approach to this problem might look like. As far as I can see there are essentially three classes of solution:
- Calculate a new orbit directly from the old orbital parameters and the thrust. I don't know how plausible calculating a delta on a Keplerian orbit is, though, and I can't find much online about doing that.
- Write code with better precision or better numerical stability for doing orbit -> pos/vee -> orbit conversion. I don't know how plausible any stability is when you're doing that fifty times a second, though. I've found some code for calculating that, but I don't know where it sits on the fast/stable/good spectrum.
- Keep my own position/velocity values for the ship, update them continually, recalculate the orbit at intervals just so the player gets some feedback. That would require implementing a general two-body problem solution, which sounds like a lot of work.
What's a good option here?