Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

share|improve this question
add comment

3 Answers

up vote 10 down vote accepted

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.

share|improve this answer
add comment

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);
}
share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.