Search Unity

Set Gravity isnt working - help please!

Discussion in 'Scripting' started by VeeooshL, Aug 28, 2015.

  1. VeeooshL

    VeeooshL

    Joined:
    May 11, 2015
    Posts:
    3
    I am having problems. I am trying to make a 2d game, and one thing that happens is gravity changing. I need my player to 'switch gravity' when up arrow is pressed (upside down) and down arrow is pressed (normal). This is my code, it is on a script which controls the player (moving, jumping, etc...):

    Code (csharp):
    1.  
    2. //
    3. if (Input.GetKeyDown (KeyCode.UpArrow))
    4. {
    5. transform.localScale = new Vector3(1f, -1f, 1f);
    6.  
    7. Physics2D.gravity = new Vector2(0,-1);
    8. }
    9. if (Input.GetKeyDown (KeyCode.DownArrow))
    10. {
    11. transform.localScale = new Vector3(1f, 1f, 1f);
    12.  
    13. Physics2D.gravity = new Vector2(0,-1);
    14. }
    15. //
    16.  
    Thanks!
     
  2. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    You use 'new Vector2(0,-1)' in both cases. One should be the opposite.
     
  3. VeeooshL

    VeeooshL

    Joined:
    May 11, 2015
    Posts:
    3

    Even then, I just float into the air. Looking at the rigidbody, the gravity scale is still 5 but it just slowly floats me into the air. As you can probably tell, im not very good at this.
     
  4. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    That's due to how physics work. You'll accelerate and if you switch the gravity to such a small opposite force, it'll take time to take the effect that you expect. You'll slowly deaccelerate until you finally accelerate again and move in the expected direction.
     
    tedthebug likes this.
  5. VeeooshL

    VeeooshL

    Joined:
    May 11, 2015
    Posts:
    3
    Is there a way to get around this? Because I don't even press any buttons, I immediately start floating.
     
  6. tedthebug

    tedthebug

    Joined:
    May 6, 2015
    Posts:
    2,570
    Do you want them to float up/ down at an increasing rate (the longer you hold the button) or sort of snap up/down like gravity guy when you press the button once)?
     
  7. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Default gravity is (0, -9.8) many 2D games go higher to make the amen appear more snappy, I've seen numbers up to 30.

    So toggle it between (0, 9.8) and (0, -9.8) for a straight swap of the default.