Gravity Engine V1.4

Full documentation and tutorials: Online Info

Gravity Engine brings full gravitational interaction for objects and particles to Unity. Masses and velocities are assigned to objects and Gravity Engine does the rest. It is highly tune-able allowing trade-offs between game play and physical accuracy.

Orbits can be defined and viewed in the scene editor.

Orbits resulting from spaceship velocity changes can be predicted and illustrated:
Screen Shot 2016-09-03 at 5.55.47 AM

Unity WebGL Orbit Prediction Scene

Custom planetary systems can be built or random ones may be created:
Screen Shot 2016-09-03 at 5.56.08 AM

Additional tutorials are available on the NBodyPhysics YouTube Channel.


54 thoughts on “GravityEngine

  1. Musketeer

    Bro you probably should target game maker’s interest instead of simply introduce orbit models…
    Go play Kerbal Space Program and some other gravity games and think about what Unity users actually want…
    For me, I need an gravity system suitable for interstellar combat, and properly optimized control code for spaceships in this environment is what I need next after a gravity system.
    I also need to optimize the law of forces deeper because the usual gravity law might not be the funnist configuration for space wars. Fun parts can come out of reality but usually not raw reality. so laws should be left for changing.

    Most Unity users use it for games, not for science. So do your plugin. Your plugin really has a potential but you need to rethink about it. If I am you, I would set my target as : a system that some like Kerbal Space Program might use it for producing games easier.

    1. Post author

      I appreciate you taking the time to provide feedback.

      I do plan on making the core code available – so developers can change the law of gravity if they wish. [EDIT: All code is available as of version 1.1]

      The tutorials perhaps over-emphasize the ability to create orbits. The asset will allow arbitrary (non-orbit) operations and does demonstrate how to adjust spacecraft orbits.

      Part of the challenge is that rocket science is, well, rocket science. Predicting the interactions of even three bodies is legendary as a source of chaotic motion. I do have a thread for what features could be added I welcome more discussion there.

    1. Post author

      Cool link. Thanks for that.

      Good advice to revisit Kerbal as well. I am looking into creating some scripts that show a projected orbit for a velocity change. I would like to then move on to transfer orbit/rendezvous maneuver sequence calculations – but I’ll need to learn some stuff to get that going.

      1. Musketeer

        Predicted trajectory of a moving object in complex gravity environment is sth I haven’t figure out how to get it done. Looking for your solution.

      2. Musketeer

        Predicted trajectory of a moving object in complex gravity environment is sth I haven’t figure out how to get it done. Looking forward to your solution.

  2. Philip Tarpley

    Hey, I just got Gravity Engine. It is pretty cool, but it appears that all properties from NBody/Orbit scripts are stored by the GravityEngine behaviour on start, and thus cannot be changed during the simulation?

    The asset would have much more utility as far as games/simulations go if the NBody/Orbit props could be dynamically changed to allow seeing how the system changes if a body’s mass/orbit changes.

    1. Post author

      Hi Philip,

      Thanks for the feedback.

      Currently you can change the velocity of a body dynamically (which will change the orbit). I had not thought in terms of changes to the orbital elements (they are currently used only to set the initial velocity) – but that is something I will look at.

      Changing the mass is something I have been meaning to do. I’ll put it in the next update.
      [Edit: This is available in version 1.2]

      I hope to submit the next update for review in about 1 week. It will have orbit projections, random system generation and some minor fixes/additions.

  3. Christopher Batih

    Hi there,

    I really like the look of this and want to make a purchase, but I have a couple of questions.

    Can I use this to simulate the movement of an object from the surface of a body to circular orbit? A spacecraft launch for example.

    Can I use this toolkit to simulate a hohmann transfer between two bodies?

    Thank you.

    1. Post author


      Apologies for the slow response – the comment pending emails to me seem to be broken.

      Yes, the asset can be used for hohmann transfers via the apply impulse function in the engine.

      I have not yet done much with starting from a surface. I think there will be a bit of new code to simplify the shift from non-orbital motion into orbital motion – so I expect I will need to make some modest changes.

      I am currently making modifications to support a variety of real-world units (currently the unit system is dimensionless with G=1 but several users have expressed an interest in entering info in kg, km, AU etc. and having Gravity Engine do the conversions).

  4. Rahul Jethwani


    I have just purchased your engine recently, and I must say I am impressed. I do however, have certain queries with which I hope you can help me

    We are using it for educational purposes to train people with the concept of orbit and gravity. We want to show the effect of what happens if the velocity of the satellite (in this case the planet) is increased at runtime (orbit-raising), or the mass of either the planet or its satellite. What would be the best way to make changes to implement this feature according to you? Will the engine be able to deliver our requirement after we make the changes?


    1. Post author

      Hi Rahul,

      There is a tutorial scene that should accomplish what you are asking. I seem to have failed to link it properly on the docs page – apologies for the omission.

      Take a look at

      Velocity can be changed at runtime with GravityEngine.instance.ApplyImpulse(…)

      Feel free to contact me at the support email if you have further question.

  5. Daniel

    I love this system! However I’ve been suffering from performance issues (less then a frame per second) when I have one sun and two planets. Any idea on why this is?


    1. Post author

      That is unexpected. If you can make a sample scene available to me via the support email ( I’d like to take a look.

      Failing that if you can provide the positions, masses, velocities of the objects and any changes to the GravityEngine defaults I can try and duplicate your issue.

  6. hersfeldtn

    Very interested in this project, a couple questions:

    -Is it possible to specify, for a particular object, which bodies are influencing it? So you could, for example, have a spaceship in solar orbit only influenced by the planets, and not by all their moons?

    -How difficult would it be to implement an orbit predictor based on n-body physics for a limited period ahead? Would it help if I keep all natural bodies in Kepler orbits?

    1. Post author

      1) Can you specify which bodies influence…
      If you gave e.g. all the moons zero mass, then they would stay in orbit around their planet and not influence other bodies. (They could be either NBody evolution or Kepler orbits).

      2) The current orbit predictor uses a single other mass as the environment. To do more than this it would be necessary to run the simulation ahead and track what happened and record it, then reset back to where you were. This could be done by spinning up another integrator for just the bodies of interest – but this is currently not supported. I’ll give it some thought….not sure how CPU-feasible it would be.

      1. hersfeldtn

        1) Is there any way to do this without changing the entire system? Ideally I’d want to be able to place multiple spacecraft at different points without each one having to worry about all the bodies in the system.

        2) If it helps, I know that Children of a Dead Earth manages to do predictions of this type, but so far I haven’t been able to figure out how.

        1. Post author

          Is the concern about limiting interaction to local bodies about CPU effort or predictability?

          If it’s predictability, one other option would be to have a force law that was gravity within a specified radius and then was zero outside of it. With the custom force laws this could be done fairly simply.

          1. hersfeldtn

            CPU effort is the big concern, although predictability also helps. The project I’m considering would, at minimum, have dozens of spacecraft moving through the solar system populated with maybe a hundred bodies. I’m trying to find any way to reduce the CPU load without resorting to patched conics.

          2. Artaani

            I am also need to lock space ship to specific objects. And set mass of Moon to 0 is not a solution, because we need to have 2 different ships, one on orbit around Earth, second around orbit of Moon, and each ship should be affected only by its central body.

            Custom force law could be a solution.
            Maybe you can implement it and add in the update? Because it is very important feature for many customers, because this is how space ships works in KSP.

            Of course such approach will disable possibility of Lagrange points, but accuracy of prediction trajectory is much more important, which is possible only for 2 body solution of course.

          3. Post author

            An alternate solution would be to make the Gravity Engine not a singleton, then you could manage things in whatever partition is required.

            I’ll add this to the backlog, but first I want to respond to the bugs you found and get the trajectory prediction work finished.

  7. Post author

    One approach used in more sophisticated NBody codes is to make a tree-based code. Each body interacts one on one with bodies in the same “box” and the effect of other boxes is based on the center of mass of the bodies in those boxes. As boxes get farther away, they get bigger.

    Another approach would be to move this into a GPU compute resource.

    It would be fun to add these to Gravity Engine – but it is nothing I can commit to in the near-term.

    1. hersfeldtn

      One last question, then I promise I’m done:

      Would it be particularly problematic to nest instances of GravityEngine? So you could, for example, place an empty object at the barycenter of each planetary system with its total mass, then put another instance there to handle that planet’s moons, with spacecraft shunted between them when they pass into the hill sphere?

      1. Post author

        Always happy to talk about gravity.

        Yes, I think that’s something that is workable. I just made a scene with two GEs (needed a slight hack, to defeat a check for this). The issue is that if a body is in more than one GE then two different engines are trying to update it’s position. It should not be too hard to find a way around this – maybe tag an object with the name of the engine that should move it. I’ll tinker a bit in the next week or two. Ping me on the support email if you want an update.

        BTW – picked up Children of a Dead Earth. Early days – but I do like what they do with orbital mechanics. I had the frame of reference change on the GE Trello board already – it’s fun to see that work.

  8. Peter D Wilson

    Surely asked before but, what comfortable compute power do I need to enjoy GravityEngine. I’m a Mac aficionado?

    1. Post author

      The compute power needed really depends on how many objects will be interacting: number of massive, massless and particles in the scene.

      Typically on my 2015 Mac running a dozen or so massive bodies and several thousand particles is never an issue, but I have not yet probed the upper limit. A performance assessment scene is on my list of features to add.

      If more performance is needed there are options to make some bodies massless, or put them in fixed orbits.

  9. Ian George

    Hello Yes this asset looks very interesting and if it could be adjusted for PC games I think this may be exactly what I need but I do wish to know if I can use surface vehicles and build bases/cities on the planets as I have a few ideas for several games the first being Battlezone 98/ 2 /Crysis /Savage/ /Uprising 1st person Shooter FPS R.T.S Games where you plane build fight and mine on a planet or even an asteroid or even a comet body and then you can take to the stars and fight in a Freespace/Wing Commander/ Eve : Valkyrie style battle with Giant Space Cruisers and Space Battleships and small one man space fighters and bombers capable of entering planetary atmospheres and fighting there.

    What I wish to know will there be the capability of creating planetary atmospheres and having sea cruisers and frigates and battleships and cruisers and carriers and submarines on Earth style planets? And I noticed that you mentioned that you would be making irregular body shapes to be used on the planetary surfaces how far are with that ? Also will it be possible to import your own planets to use with this asset ?

    1. Post author

      Thanks for your interest.

      The gravity engine is better suited for space-level insteractions (planets, ships etc.) and not near surface interactions. There is no direct support for atmospheres – but there is an example scene that shows how to setup decay in an orbit – which will accomplish this.

      Based on your description (near planet gravitation field, surface interactions) gravity engine is not a great fit.

      (I am interested in a surface gravity of weird surfaces asset – but it is still just an idea at this point.)

      1. Ian George

        Ahh what a shame as I see on your asset store page someone else was interested in That and I am definitely interested in fighting in Space and fighting on on a planet on the same level I see some games like Empyrion Galactic Survival can already do this and I would like this for my games I shall also leave some links to the other games I have mentioned so you get an idea of what I am talking about I am also interested in your ”weird surfaces” idea what exactly is that then ?

        Empyrion Galactic Survival

        Battlezone 98 Redoux

        Battlezone II: Combat Commander

        Uprising Join or Die

        Uprising Lead And Destroy

        Savage Resurrection

        Savage: The Battle for Newerth PC Games Trailer


        Decent Freespace

        Freespace 2

        Wing Commander 3

        Eve : Valkyrie

        And with my game you would be able to walk about on Space Carries and Space Battleship/Cruiser Frigates e.t.c in the 1st person or 3rd person fly around in Space and fight in all areas get into and out of vehicles and fight in them and well with my game have an auto ject when your vehicle is destroyed yes kind of like Battlezone Hopefully you might make the Gravity Engine enabled so we could have surface vehicle and human /alien interaction with the planets I will definitely keep an eye on this asset with great interest

        1. Post author

          Thanks for taking the time to provide the references. I’ll try to find some time to explore them!

        2. Post author

          I didn’t answer your weird surface question.

          Motion *on* a 2-surface requires objects follow the natural geometry of the surface. I tinkered with this in my game Geodesic Asteroids, which I blogged about here and is available on iOS and Android.

          I am contemplating making this more general – and ideally supporting motion on an arbitrary smooth mesh or any of the standard mathematical 2 surfaces (torus, ellipsoid etc.). I think it would be fun to make an asset that allowed developers to do this.

  10. Artaani

    It looks amazing! I surprised that I found such tool on the Asset Store, it seems like it is exactly what I need!

    I am already developed my own system about orbits, but it is quite raw. Seems like your system is far more advanced and more polished, and you are definitely know what you are doing.

    I not purchased this asset yet, but I want to ask a few questions:

    1. Is it possible to hover cursor on specific point on trajectory and get its parameters (namely, I want to know a time when body will arrive at this point). Or is it possible to implement such functionality with not too much efforts? Will you help me with code if it will be necessary?

    2. Is there a function which will return a position and velocity of body at specific time? For example I have ISS, I know its position and velocity, I want to know its position and velocity after 30 minutes, or after 2 years, or any number.

    1. Post author

      For (1) I am working on code to do trajectory prediction. This is full N-body compute ahead – so it is not restricted to elliptical orbits. These points are already tagged with time so implementing something that displays this should be straight-forward.

      For (2), it should be possible to use make some modifications to an OrbitPredictor to allow this – but the support is not currently there. I will add it to my back log – but am happy to help you code it if you’re keen to get it sooner than that.

      1. Artaani

        Hello! I have another question.

        There is a text in description on the Asset Store:
        “highly accurate double-precision physics”
        I assume you are using custom “Vector3” type which consist from double X Y Z (not float), right?
        Let’s call it “Vector64”.
        So, how can I get a Vector64 position and velocity of specific body?

        And also, can I get a various parameters of orbit, for example, semi-major axis or eccentricity? It is also in double?

        1. Post author

          There is an internal double[,] representation for positions and velocities in each integrator.
          (There are three types of integrator you can choose from based on CPU/performance needs of your game). The positions are held in the GravityEngine class and the velocities are held in the integrators. To update the scene these are cast back into floats. It would be trivial to add a GetDouble() for this. I chose not to add a Vector64, since each computation would involve multiple dereferences of the x,y,z so I kept arrays. Arrays are the standard approach in this kind of numerical computing. Velocities are also mapped back into a Vector3, but the underlying double[] values could be retrieved.

          Orbit parameters can be set as floats in e.g. OrbitEllipse, or read back from an OrbitPredictor. The precision of floats has been ok.

          1. Artaani

            Wow, some interesting optimization technique! I didn’t know this.
            Performance it is good!
            I will definitely buy this asset next month.
            Thanks you for quick reply. Support is amazing : )

    1. Artaani

      During tests, I managed to make it work, but only once and I don’t have an Idea how, but after I changed something, it stopped worked again. Some kind of magic : )

      1. Post author

        Thanks for the test scene, I’ll take a look this evening.

        One comment: if you have other massive bodies in the system, then the orbit prediction (which is based in a two-body calculation) will not show the correct trajectory if the other masses have a significant effect. This is the reason I am coding an N-body look ahead trajectory prediction (which is very close to done).

        1. Artaani

          In my scene, the is only 1 star in the center.

          Two body solution is okay, it is exactly what I need, so it is not a problem.

          By the way, is there a possibility to lock space ship to specific center body? But it still should be controllable (like in KSP, where space ship affected only by single body (if it located in its sphere of influence)

    2. Post author

      Yeah, that’s a bug. I’ll grab the Unity project and see what’s up. Is the body in Kepler mode or GE mode?

  11. Artaani

    Setting of time scale also does not work as intended.

    1. If Evolve Mode of my celestial bodies set to GRAVITY_ENGINE, it works, however each time when I press faster or slower, the speed is not changed instantly, it is very slow at beginning and it became faster over short time. (it is not desired behavior)

    2. If Evolve Mode of my celestial bodies set to KEPLERS_EQN, each time when I change time scale, all celestial bodies returned back to their initial position (phase) and going to move from initial position again (this is not correct, they should continue from the same phase when they are)

    Note, item 2 is more important for me, because I need to keep all celestial bodies exactly in KEPLERS_EQN mode.

    Can you please help with this too?

    1. Nbody

      Happy to help.

      Can you please send me a few details at
      1) Can you please confirm which scene you’re using faster/slower in?
      2) when you say “short time” before you see the speed change can you estimate how long this is? Less than a second?
      3) I will investigate the interaction of fast/slow and Kepler mode – sounds like a bug based on your description.

      1. Artaani

        Just sent you an email with video and Unity project.

        1. TestScene in the root. But issue persist in your Demos scene too.
        2. Yes, 1-2 seconds, it is visible on video.

  12. Artaani

    Another question.

    Can you please describe in more details, how can I get position and velocity of specific body in double?

    I asked about this earlier and you said something about integrators, but it is very hard to find specific thing in such complex code. I tried to find double[,] variable, but there is a lot of them.

    Possibility to get various parameters from the engine, is extremely important, because we need not only to observe nice celestial motion, but also work with complex numbers. We are working on education project so it is very important.

    So, can you please show a code for the next things? Also it would be nice to have nice API for such things in the next version.

    1. Get position of Nbody in double.
    2. Get velocity of Nbody in double.

    3-8. Get all elements of orbits:
    – Semi major axis
    – Semi minor axis
    – Eccentricity
    – Current anomalies (phase)
    – Inclination
    – Period
    etc, the more, the better

    So will be nice to have something like:
    double[3] = NBody.GetPosition ()
    double[3] = NBody.GetVelocity ()

    double = ElepticalOrbit.GetSemiMajorAxis ()


  13. Bill Petro

    Love this so far. I am having an issue with Trajectory prediction. It does not work if I have Kepler objects in the scene ? If i make it gravity engine update it works. I really would prefer to have kepler for the planets (assume this is faster and dont want my planets getting out of whack). Is this just a bug? Seems trivial to add, so maybe i am doing something wrong. Having fun so far!

    1. Post author

      That’s an oversight (bug). I did not code trajectory paths for Kepler objects. I can do that.
      Please contact the support email and I can arrange to send you a patch once it’s done.

  14. Russ

    Your asset provides simple methods of adding asteroids, comets and planets but I don’t see a simple method of adding any moons. Am I missing something?

    1. Post author

      Perhaps more a case of my not making it easy enough to find…

      Moons are supported. The orbit ellipse script will default it’s center object to the parent object (if the parent has an NBody component). An example of this can be found in the T2-Orbits scene where there is a moon around the first planet (which is itself a child of the star).

      Alternatively, these could all be top level objects and the center objects for each could be explicitly specified in the inspector. Then the moon would indicate it’s center object is the planet.

      Hope this helps.


Leave a Reply to Russ Cancel reply

Your email address will not be published. Required fields are marked *