14
\$\begingroup\$

I have two spheres in Unity. One is 1000x in size other is 1x in size. So I want the smaller sphere to be attracted to bigger sphere. So how do I do it. I know that it can be down through gravity using rigid body. But how do I change gravity angle towards the big sphere?

\$\endgroup\$

7 Answers 7

21
\$\begingroup\$

Gravity in the Unity physics engine only goes in one direction and is controlled in the Physics menu in the Edit->Project Settings menu.

enter image description here

If you want to do something other than that, you'll have to implement your own gravity.

Basically, you can add a sphere collider on the object you want to be the center of gravity. The collider should encompass the entire area where you want objects to be affected by the gravity of that object. Whenever an object collides with this "sphere of influence", you apply a force to it. You continue to apply a force to it as long as it's inside the sphere of influence.

The gravitational constant you use can be tweaked by you, but the standard one used for calculations in the real world is:

F = Gm1m2/r2

Spelled out that's:

Force = Gravitational constant * mass of object 1 * mass of object 2 / the distance between the two objects squared.

Do note that Gravitational constant is not 9.81. That's the acceleration caused by gravity at the earth's surface.

\$\endgroup\$
2
\$\begingroup\$

In fact, I'm currently working on a game based around gravity: simply, you place stars to move your player through eliptical orbits and the slingshot effect. I disabled gravity, and used this code:

using UnityEngine;
using System.Collections;

public class PlanetGrav : MonoBehaviour {

    //Declare Variables:

//Strength of attraction from your sphere (obviously, it can be any type of game-object)
    public float StrengthOfAttraction;

//Obviously, you won't be using planets, so change this variable to whatever you want
    GameObject planet;

    //Initialise code:
    void Start () 
    {
        //Again, you can change the tag to whatever you want.
        planet = GameObject.FindGameObjectWithTag("Planet");
    }

    //Use FixedUpdate because we are controlling the orbit with physics
    void FixedUpdate () {
        //Declare Variables:

    //magsqr will be the offset squared between the object and the planet
        float magsqr;

        //offset is the distance to the planet
        Vector3 offset;

        //get offset between each planet and the player
        offset = planet.transform.position - transform.position;

            //My game is 2D, so  I set the offset on the Z axis to 0
            offset.z = 0;

            //Offset Squared:
            magsqr = offset.sqrMagnitude;

            //Check distance is more than 0 to prevent division by 0
            if (magsqr > 0.0001f)
            {
//Create the gravity- make it realistic through division by the "magsqr" variable

rigidbody2D.AddForce((StrengthOfAttraction * offset.normalized / magsqr) * rigidbody2D.mass);
            }
        }
    }
}

PS The code originally looped through an array of all the planets: this is edited and therefore may not be fully correct. It should be okay though.

\$\endgroup\$
1
\$\begingroup\$

There's no need to resort to the gravitational equation. Acceleration due to gravity is constant regardless of mass, so all you want to do is accelerate your small objects towards the large-object each frame.

The code would look something like this:

public void FixedUpdate()
{
    rigidbody.velocity += gravitationalAcceleration * Time.fixedTime * (largeObject.transform.position - transform.position);
}
\$\endgroup\$
1
  • \$\begingroup\$ But that would just cause an object fall on the planet instead of orbiting it \$\endgroup\$
    – DataGreed
    Commented Jan 8, 2021 at 2:48
1
\$\begingroup\$

I've been working on a similar project based in Zero-G in which I need all game objects to generate and react to both gravitational and electromagnetic force based on their volume, density, mass, energy and conductivity. I'm relatively new to scripting, but I've made a few modifications to the script above to make it work for me in a 3D space (as far as gravity is concerned... almost...):

using UnityEngine;
using System.Collections;

public class DynamicWeightAnalysis : MonoBehaviour {

//Declare Variables:
//BBB adding volume calculations
//NOPE
//BBB adding density (...does nothing yet...)
public float density;

//BBB NOPE!

//Strength of attraction from your game-object, ideally this will be derived from a calculation involving the objects volume and density, but for now it's entered from the inspector)
public float RelativeWeight;

//BBB Here, we name our target object (s)
GameObject blockALPHA;

//Initialise code:
void Start () 
{
    //BBB here, we define our target object by searching for its tag (setup in editor)
    blockALPHA = GameObject.FindGameObjectWithTag("Block ALPHA");
}

//Use FixedUpdate because we are controlling the orbit with physics
void FixedUpdate () {
    //Declare Variables:

    //magsqr will be the offset squared between the object and the planet
    float magsqr;

    //offset is the distance to the planet
    Vector3 offset;

    //get offset between each planet and the player
    offset = blockALPHA.transform.position - transform.position;

    //Offset Squared:
    magsqr = offset.sqrMagnitude;

    //Check distance is more than 1 to prevent division by 0 (because my blocks are all 1x1x1 so, any closer than 1 and they'd be intersecting)
    if (magsqr > 1f)
    {
        //Create the gravity- make it realistic through division by the "magsqr" variable

        GetComponent<Rigidbody>().AddForce((RelativeWeight * offset.normalized / magsqr) * GetComponent<Rigidbody>().mass);
    }
}
}

As you can see, I'm still working on it, basically all my additions so far, annotated with "BBB", aren't yet functioning as I'd like. But as it stands, it allows my "block ALPHA" objects to interact gravitationally in 3d with other "block ALPHA" objects in a fairly predictable way. (although, when placing two or more blocks, the last one is always the "attractor" and will remain stationary until a collision occurs. which I am working on... help would be appreciated :) ) Hopefully that helps..

\$\endgroup\$
3
  • 1
    \$\begingroup\$ If you want to ask a question, post it as a question please, don't bury it in your answer. \$\endgroup\$
    – user1430
    Commented May 19, 2016 at 4:04
  • \$\begingroup\$ my bad, thanks for taking care of it, won't happen again :) \$\endgroup\$ Commented May 20, 2016 at 18:12
  • \$\begingroup\$ Thanks this helped me, worked fine in 2d space for me. \$\endgroup\$
    – Mastro
    Commented Aug 2, 2020 at 1:52
0
\$\begingroup\$

Have the planet/big sphere with an circle collider, give it a child. Now, the planet should either be tagged planet or static cosmic object, and the child should be labeled Area of influence. Now the small object should have a rigidbody and a sphere with a isTrigger.

Put a script on the planet with a on enter/enterstay trigger, if it is a sphere of influence it should be pulled towards that.

Else you can do it the other way around. But in any case this would probably be better since you most likely want to make gravitational pull different from planet to planet.

\$\endgroup\$
-2
\$\begingroup\$

What others said, gravity on unity is only towards a certain direction, so maybe you should instead disable gravity completly and script a force that moves the small sphere towards the huge one.

\$\endgroup\$
-3
\$\begingroup\$

If you want change gravity for specific plane you could use this script attach to plane.

using UnityEngine;

public class ChangeGavityToThisObject : MonoBehaviour
{

    private Quaternion rot;
    private Vector3 gravityValue;

    void Start()
    { 
        gravityValue = Physics.gravity;      
    }

    void Update()
    {
        rot = GetComponent<Transform>().rotation;
        Physics.gravity = rot * gravityValue;
    }
}

GetComponent is in Update, because i want to make possibility to change rotation this plane in game.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ This changes the direction of the global gravity. Not just for one object. \$\endgroup\$
    – Philipp
    Commented Mar 24, 2020 at 11:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .