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

Double jump. What to use?

Discussion in 'Physics' started by Eucalyp, Jan 6, 2020.

  1. Eucalyp

    Eucalyp

    Joined:
    Nov 4, 2019
    Posts:
    8
    Hello,
    I'm doing my first 3d game in unity, it's a parkour game and I'm trying to make the player (a simple capsule) being able to double jump. I'm currently using "ForceMode.VelocityChange" , it's working very well for the first jump, but for the second jump, depending of if the player is going up or down, it's going really high or it just give a little impulsion. I want to know if there is an alternative script to use, so the jumps are constant.
    Hope I've been clear!
    thank you
     
  2. Edy

    Edy

    Joined:
    Jun 3, 2010
    Posts:
    2,434
    VelocityChange is just that, a velocity change. That is an addition to the actual velocity. The resulting velocity is the sum of the actual velocity and the AddForce parameter. Achieving a specific velocity requires you to account for the actual velocity. For example (pseudocode):

    AddForce(desiredVelocity - currentVelocity, ForceMode.VelocityChange)
     
  3. Eucalyp

    Eucalyp

    Joined:
    Nov 4, 2019
    Posts:
    8
    thank you, sorry, I'm a beginner, this is my line of code currently:

    rigidBody.AddForce(Vector3.up * jumpSpeed, ForceMode.VelocityChange);

    "jumpSpeed" is the velocity that I want, what should I write?

    thank you
     
  4. tjmaul

    tjmaul

    Joined:
    Aug 29, 2018
    Posts:
    464
    try the following:

    Code (CSharp):
    1. float yVelocity = Mathf.Clamp(rigidBody.velocity.y, rigidBody.velocity.y, 0);
    2. rigidBody.AddForce(Vector3.up * (jumpSpeed - yVelocity), ForceMode.VelocityChange);
    As Edy already explained, you're just adding velocity. If your rigidbody is on its way down, adding upward velocity will just make it fall slower. But if you also account for the current y-velocity you can make sure, that the y-velocity of your character is zero so you can guarantee a certain y-velocity after you pressed jump. It's just condensed to one line, but that's conceptually what happens.

    The clamp in the first line serves to avoid that when you double jump while your character is still on its way up, it flies way higher than expected. You can also just remove the clamp and replace by
    float yVelocity = rigidbody.velocity.y
     
    Edy likes this.