2D jump function C#

Hello and good afternoon!!
I got a little problem with an jump function that i want to implement in my C# controll script for a 2D platform game. I’ve tried to use a lot of advice from some topics of the forums and answers section, but almost none had any kind of information that i was looking for. What i would like to know is that "the player jumps by pressing an KeyCode; while ( in the air and keypressed ), the player falls slowly; if ( player releases key), he falls normally until hitting the ground. " Please … Help !!

An example ill give is the jump function from the Zombie Tsunami game :

void Jump()
    {
       
        rb2d.AddForce(Vector2.up * jumpForce);

        float currentForce = jumpForce;

        while (Input.GetKey(KeyCode.Space) && currentForce > 0)
        {
            rb2d.AddForce(Vector2.up * currentForce);

            currentForce -= decayRate * Time.deltaTime;
        }
    }

    private void Planagem()
    {
        rb2d.GetComponent<Rigidbody2D>().drag = 12;
    }

    private void Run()
    {
        grounded2 = Physics2D.OverlapCircle(GroundCheck2.position, 0.2f, chao);

        grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));

        if (transform.position.y <= -3)
        {
            print("Dead");
            //playerAnimator.SetTrigger("Dead");
            Time.timeScale = 0;
            panel_dead.SetActive(true);
        }
    }

    public void btt_restart()
    {
        SceneManager.LoadScene("jogo");
    }

For one thing your while loop will run so long as you’re holding down space in the frame that you called Jump(), i don’t believe this is your intent, try adding a force when space pressed in your update function and than remove that force when space is released.

2 Likes

Also, for fine jump control, I’d recommend ditching the physics engine. In this article, I have a jump function that works exactly as you describe — you can jump higher by holding the jump key, or press it quickly for a smaller hop. It even supports double-jumping (while disallowing triple- or more-jumping), and allows you to influence your direction while in the air. The result is a very responsive, Mario-like feeling… and it was only easy to achieve because I wrote my own physics.