Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Setting the gravity of an object

Discussion in 'Getting Started' started by Mucmab11, Mar 19, 2015.

  1. Mucmab11

    Mucmab11

    Joined:
    Mar 19, 2015
    Posts:
    3
    Hi guys!

    How can I set the gravity of an object in an event that gets called when you touch/click at the screen?

    Thanks
     
  2. Jaimi

    Jaimi

    Joined:
    Jan 10, 2009
    Posts:
    6,171
    reversstorm and Ryiah like this.
  3. Ness

    Ness

    Joined:
    Oct 1, 2012
    Posts:
    182
  4. Effervescent

    Effervescent

    Joined:
    Mar 7, 2015
    Posts:
    31
    The OP wants to change the gravity experienced by the object, not the mass. Changing the mass of an object would not affect the acceleration experienced by it.

    I find it strange that there is no 3D equivalent of Physics2D.gravity (or maybe I just haven't worked with 3D enough!). I think the solution to the OP's problem is using Rigidbody.Addforce with Forcemode.Acceleration.
     
    ttimothyt2 and PlayCreatively like this.
  5. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,141
    There are two ways to add gravity to an object. The method mentioned by @Jaimi is the way to apply gravity on a global scale. If you want a different gravity setting for one or more objects though, you can add a Constant Force at runtime and adjust accordingly.
    Code (csharp):
    1. public ConstantForce gravity;
    Code (csharp):
    1. gravity = gameObject.AddComponent<ConstantForce>();
    2. gravity.force = new Vector3(0.0f, -9.81f, 0.0f);
    Keep in mind if you use the local method without disabling the global method for your object (through useGravity), you'll have both effects at once.
    Code (csharp):
    1. gameObject.GetComponent<Rigidbody>().useGravity = false;
     
    Last edited: Mar 23, 2015
  6. WILEz1975

    WILEz1975

    Joined:
    Mar 23, 2013
    Posts:
    368
    Just add an exponential down force ...

    Code (CSharp):
    1.    
    2. public float GravityMultipler;
    3. float AddGravity;
    Code (CSharp):
    1.     void Update()
    2.     {
    3.             AddGravity += GravityMultipler;
    4.             _rigidbody.AddForce((Vector3.down * AddGravity), ForceMode.Acceleration);
    5.  
    6. ......
    So you can maintain normal gravity to everything else.
     
    ItsDeafy likes this.
  7. nathanaelkinnis

    nathanaelkinnis

    Joined:
    Sep 24, 2020
    Posts:
    4
    For anyone still looking for this, check this out:
     
    ThaiTu999 likes this.