Gravity in x direction

Hi,

I have an object wich uses the “Rigidbody2D”-component and the GravityScale is set to 3. How can I create the exact same gravity-force in x direction for another object?

thanks and greetings
J.

use Rigidbody.AddForce to generate the force you need in the direction you want

But how can I get the same gravity force like with “gravity Scale”? I think : rigidbody.AddForce(new Vector3(0,-3,0))
has not the same force like when my rigidbody has a: “gravity Scale: 3”?

You’ll need to manage gravity yourself if you want it to point in different directions for different objects.

public Vector3 gravityDirection = new Vector3(0,-1,0);
public float gravityStrength = 9.8f;
public float gravityScale = 1.0f;

private Rigidbody body;

private void Start()
{
   body = GetComponent<Rigidbody>();
   body.useGravity = false; // Don't use default gravity, we're managing it ourselves
}

private void FixedUpdate()
{
   // Optionally, you could normalize the gravity direction to make sure it always has length 1
   body.AddForce(gravityDirection * gravityStrength * gravityScale, ForceMode.Acceleration);
}
1 Like

Gravity scale (i’d assume, dont actually know as im a 3D dev) is multipling the glabal value of gravity by your factor.
So if you gravity is 10, setting the scale to 3 is effectivly making gravity 30 for this object.

Im sure the docs can clear this up in a second

Thanks guys! I also discovered: “Component - Physics2D - ConstantForce2D”
Where is the difference between this method and:

body.AddForce(gravityDirection * gravityStrength * gravityScale, ForceMode.Acceleration);

this method?

With the above line you have to actually DO the .AddForce every frame to keep up a force.

If instead you add a ConstantForce2D object to a GameObject with a Rigidbody2D, you can just forget about it and that object will experience a force on it continuously according to what is set in the ConstantForce2D object.

That’s pretty neat, and probably one of the easiest ways to give each object its own custom gravity. All other physics operations are still in effect (bouncing, collisions, etc.) so it will be “right.”

Obviously if you want an object to NOT experience the global gravity, uncheck the gravity property in the rigidbody.

Also, to simulate gravity you would set the .force value, which do not change when the object rotates. If you want the object always accelerate relative to how it is facing, then use .relativeForce, like for a bottle rocket always going in the direction of its nose, which might get steered sideways, for instance.

Ah awright, thank you, so as I understand the line above is a little bit more flexible than ConstantForce2D. Is there a difference between the two methods when it comes to performance?