Gravity Wars like physics

Hi,

I’d like to include gravity that attracts towards a small number of static objects in a 2D game, a bit like the old Gravity Wars game where you shoot around planets, but am not sure how I would achieve that in Unity. All the tutorials on gravity are for single directional gravity. Suggestions for how to approach this are welcome.

thanks

Chloe

I’m not quite sure, didn’t play Gravity Wars, but what is gravity? It’s a force from an upper point to a bottom point (figurally).
So you can make this gravity by getting an upper point (your object) and a bottom point (the center of some playen), then move your object in this direction.

OK - so you are saying I calculate the accelleration myself (for each object I want to accellerate towards the gravitational attractors? Easy enough, it makes sense, I did think that would be one way, just feels like I’m doing work that might be done by the physics engine in Unity? I’ll give it a go.

Chloe

Well… it will and it wont.

you will be better to use physics forces to move your stuff, but there is no ‘center of gravity’.

you will need to calculate the vector and apply the force yourself.

First thing you’ll have to do is check what is the position of the object compared to the center of gravity, then just change the position of the object towards the center of gravity

I feel that I should be able to answer this, what with currently working on a “Gravity Wars” update and all. The funny thing is, I haven’t a clue how you should do this in Unity using unity physics. Because I started work on Mammoth Gravity Battles in another game engine, I have built my own physics engine, so my way of doing many body gravity is probably not what you want.

As others have said, I would suggest using vectors to calculate distances to each planet, then use newtons law of gravitation ( F= G M m /r ^2 ) to calculate each force and apply the force.

This is definitely what you would want to do. In order to optimize that, you want to treat each interaction as a pair between two bodies, and assign opposite forces (obeying Newton’s 3rd law). Here’s an example in UnityScript - bodies refers to an array of rigidbodies that influence each other.

function FixedUpdate () {
  for (var i = 0; i < bodies.Length; ++i)
  {
    var bodyA : Rigidbody = bodies[i]; 
    
    for (var j = 0; j < bodies.Length; ++j)
    {
      // Skip double tests for pairs
      if (j >= i)
        continue;
      
      var bodyB : Rigidbody = bodies[j];
      var offset : Vector3 = (bodyB.position - bodyA.position);
      var force : Vector3 = offset/offset.sqrMagnitude;


      // Add forces to both bodies
      bodyA.AddForce(force * bodyB.rigidbody.mass);
      bodyB.AddForce(-force * bodyA.rigidbody.mass);
    }
  }
}