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. Dismiss Notice

Player jump : the better method ?

Discussion in '2D' started by MisterX_Dev, May 4, 2014.

  1. MisterX_Dev

    MisterX_Dev

    Joined:
    Apr 6, 2014
    Posts:
    8
    Hello everyone, I should include in into my hero of my 2d game the jump function. It has an rigidbody2D with gravity = 30. Thought I'd put this code in FixedUpdate script attached to the character:

    Into Update method I control if the user push the Space bar for jump, if it' true a set bool jump to true and then

    Code (csharp):
    1.  
    2. if (jump) rigidbody2d.Addforce (transform.up * jumpPower);
    3.  
    4. //And then I control if the hero Y position is over the camera size
    5.  
    6. if (transform.position.y >= Camera.main.getComponent <Camera>.orthograficSize)
    7. jump = false;
    8.  
    9. / / At this point the gravity = 30 brings it down
    This method is good for you ? Is there any other better method? Why I must set gravity to 30 if the hero's mass is 1 ? It should not be hero mass = 1 and gravity = 1?

    Thank you
     
    Last edited: May 4, 2014
  2. Invertex

    Invertex

    Joined:
    Nov 7, 2013
    Posts:
    1,495
    Where did you read that the gravity scale should be 30? You shouldn't need to touch the gravity scale in most cases, except for very specific jumping styles.

    Don't constantly AddForce for a jump, that looks unrealistic, a jump, just like in real life, is 1 instance of force from the ground, and the rest is just the person/player's velocity allowing them to move upwards, until gravity finally brings them back down.

    You can simply do:
    Code (csharp):
    1.  
    2. if(jump)
    3. {
    4. rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x,jumpPower);
    5. jump = false;
    6. }
    Just leave your gravity as 1-9 or around there, you shouldn't need gravity 30, unless perhaps you're using a very massive scene scale, which you shouldn't be.
     
  3. MisterX_Dev

    MisterX_Dev

    Joined:
    Apr 6, 2014
    Posts:
    8
    But with gravity set to 1 the player not jump... I have also set jumpPower to 1000f but it not work :-(

    EDIT : The problem was that into my Animator Controller was checked Apply Root Motion now it work fine with gravity 1 ! Thanks!
     
    Last edited: May 4, 2014