Search Unity

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,208
    grayboulware, 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:
    21,203
    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:
    375
    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.