How to make a controlled jump with a space in Unity? It is necessary that the longer you hold the space, the higher the character jumped. I sort of did it, but the height of the jump is constantly different, I don’t know why this happens. I wish it worked fine.

isGround = Physics2D.OverlapBox(player.position + new Vector3(0, 0.01f, 0), new Vector2(0.065f, 0.01f), 0, LayerGround); if (isGround && Input.GetKeyDown(KeyCode.Space)) { maxYpos = player.position.y + JumpHeight; isJump = true; } if (player.position.y > maxYpos || Input.GetKeyUp(KeyCode.Space)) isJump = false; if (isJump) rb.AddForce(new Vector2(0, JumpPower)); 

    1 answer 1

    Enter the parameter - the time during which pressing the jump button adds power. (MaxJumpTime) in the future it is better to translate it into MaxJumpHeight.

      [Header("Behavior")] public float JumpPower = 0.25f; public float MaxJumpTime = 0.25f; private float _StoreMaxTime; private bool jumping = false; private Rigidbody2D rb; [Header("Settings")] public LayerMask mask; public float CheckExstends; void Start () { rb = GetComponent<Rigidbody2D>(); _StoreMaxTime = MaxJumpTime; } void Update () { var isGround = Physics2D.Raycast(transform.position, Vector3.down , 1 * CheckExstends, mask); if (isGround && Input.GetKeyDown(KeyCode.Space)) { MaxJumpTime = _StoreMaxTime; } if (Input.GetKey(KeyCode.Space) && MaxJumpTime > 0) { MaxJumpTime -= Time.deltaTime; rb.AddForce(new Vector2(0, JumpPower),ForceMode2D.Impulse); } if (Input.GetKeyUp(KeyCode.Space) && !isGround) { MaxJumpTime = -1; } } private void OnDrawGizmosSelected() { Gizmos.DrawLine(transform.position, transform.position + (Vector3.down * CheckExstends)); } 

    From the editor, it is necessary

    • Update layer to match the ground layer.

    • Set the value of CheckExstends (Gizmo - white line in the editor window) This is a check for touch with the ground. The line should barely extend beyond the object.

    • The same thing happens - the height of the jump is different each time. Sometimes a little more, sometimes a little less. I think this is related to AddForce. Is it possible to replace AddForce with something else? - Alex
    • Is JumpPower changing somewhere else? - Egor Bashinsky
    • No, it does not change - Alex
    • Moment, I check something, there is a suspicion that this is a Grounded check - - Egor Bashinsky
    • That's right, I replaced AddForce with velocity, the result is the same. How can you check whether a character is on the ground differently? - Alex