unity-game-engine2d

rapidly increasing gravity making the jump not work


Im making a flappy bird clone for practice and while making the jump feature im having issues because at the start the jump works but then gravity gets so strong that even if im still moving upwards jumping becomes increasingly more difficult (even on 0.25 or adding like 5k force onto the y coordinate)

looked up a few solutions and found that turning off gravity when the jump button is pressed but i dont think it works for RigidBody2D that well and another solution I tried is to bump up the upwards force but that only works as a short time solution idk where to put the code so im putting it here

using UnityEngine;

public class PlayerJump : MonoBehaviour
{
    public Rigidbody2D rb;
    public float jump = 10f;
    public float Flyspeed = 10f;

    // Update is called once per frame
   void start()
    {
        rb = GetComponent<Rigidbody2D>();
    }
   
   
    void Update()
    {
       rb.AddForce(new Vector2(Flyspeed * Time.deltaTime, 0));
       
        if (Input.GetKeyDown("w"))
        {
           rb.AddForce(new Vector2(0, jump * Time.deltaTime));
           rb.useGravity = false;
        }
        else
        rb.useGravity = true;
    }
}

Solution

  • Instead of using forces, you can change the velocity of the rigidbody like this:

    using UnityEngine;
    
    public class PlayerJump : MonoBehaviour
    {
        public Rigidbody2D rb;
        public float jumpForce = 10f;
        public float flySpeed = 10f;
    
        void Start()
        {
            rb = GetComponent<Rigidbody2D>();
        }
    
        void Update()
        {
            rb.velocity = new Vector2(flySpeed, rb.velocity.y);
    
            if (Input.GetKeyDown(KeyCode.W))
            {
                rb.velocity = new Vector2(rb.velocity.x, jumpForce);
            }
        }
    }
    

    This ensures a more direct approach, whithout the need to use a time-based solution.

    Also, I corrected a typo in the Start() method—your original function was written as start() which prevented Unity from detecting automatically your Rigidbody2D.