Trade secret.
Not really, I just tracked the distance from the star and either recorded the current distance or anchored to the nearest orbit when the distance starts growing hence it starts looping around instead of flying past. It was originally meant to be more complicated but figured it might've taken too much time and might've made the gameplay too chaotic.