Search Unity

Inconsistent jump height

Discussion in 'Physics' started by pblpbl, Jun 24, 2022.

  1. pblpbl

    pblpbl

    Joined:
    Sep 1, 2019
    Posts:
    15
    I was testing jump heights for a 3D platformer game I'm making with double jump and found that the height the player achieves doing a grounded jump was slightly different than jumping in mid-air. More specifically, I considered the following player logic attached to a capsule with standard size on a cube at (0, 0, 0).
    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class player : MonoBehaviour
    7. {
    8.     private Rigidbody rb;
    9.     public float maxHeight;
    10.     // Start is called before the first frame update
    11.     void Start()
    12.     {
    13.        rb = GetComponent<Rigidbody>();
    14.     }
    15.  
    16.     // Update is called once per frame
    17.     void Update()
    18.     {
    19.         if(Input.GetKeyDown(KeyCode.Space)) rb.AddForce(Vector3.up*(5-rb.velocity.y), ForceMode.Impulse);
    20.     }
    21.     void FixedUpdate() {
    22.         maxHeight = Mathf.Max(maxHeight, transform.position.y);
    23.  
    24.         rb.AddForce(Vector3.down*5, ForceMode.Acceleration);
    25.     }
    26. }
    27.  
    I tracked the max height for each jump and found that the player jumped 2 units for the first jump, but the second jump was around 2.4 units, even though I am adding almost the same force with each jump. How can I make the jump heights of the two jumps exactly the same? Is this a quirk with the physics system?
     
    Last edited: Jun 24, 2022
  2. r31o

    r31o

    Joined:
    Jul 29, 2021
    Posts:
    460
    You are adding force by doing:
    Code (CSharp):
    1. Vector3.up * (5 - rb.velocity.y)
    When doing that the second jump will be smaller if the player still goes upwards, and bigger if is falling.
    Instead you should do:
    Code (CSharp):
    1. Vector3.up * 5
    But this will make the jump still inconsistent, so you also have to do:
    Code (CSharp):
    1. rb.velocity = new Vector3(rb.velocity.x, 0, rb.velocity.z
    This will reset the y velocity of the rigidbody.
    Also, that code allows you to make infinite jumps