Search code examples
c#unity-game-enginegame-physicsgameobjectrigid-bodies

Horizontal gravity on a gameObject in Unity


im making a simple 2D game.

I have a gameobject with a rigidbody component.

The standard rigidbody gravity pull down my gameobject, but i want the gravity to pull the gameobject to the left instead.

I know how to set the gravity to pull left in edit -> project setting ->... but this setting will change the gravity to all rigidbody which is a problem in my case.

I just want to set the gravity for 1 gameobject.


Solution

  • Since you are making a 2D game, I assume your GameObject has a Rigidbody2D component attached. Set the gravity scale on that to 0. Also attach a ConstantForce2D to your GameObject and apply your gravity in Force -> X. To get the same amount of force as the gravity, you have to multiply your gravity (probably 9.81) with the mass of your GameObject. If your custom gravity or the mass of the GameObject changes from time to time make sure to calculate that in your update method, then apply it to the ConstantForce2D component. That could look something like this:

    Rigidbody2D playerRigidbody;
    ConstantForce2D customGravity;
    
    void Awake () {
        playerRigidbody = GetComponent<Rigidbody2D> ();
        customGravity = GetComponent<ConstantForce2D> ();
    
        float gravityForceAmount = playerRigidbody.mass * Physics2D.gravity.magnitude;
        customGravity.force = new Vector2 (-gravityForceAmount, 0); // gravity to the left
    }
    
    void Update () {
        if(mass or gravity changes)
            modify the constant force;
    }