Search code examples
c#unity-game-enginegame-physics

Unity Jumping Mechanic not working


I have a game in a 3D space, and rigidbody comp. to a player. I have implemented a jump mechanic that is not working at intended, with this code:

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{

    public bool Travel;
    public Rigidbody rb;
    public Transform tf;
    public bool Grounded;
    public float speed;

    int OnRail = 2;

    void Update ()
    {
        float speed = 1f * Time.deltaTime;
        if (Input.GetKeyDown("d") && OnRail < 3)
        {
            tf.Translate(5.4f, 0f, 0f);
            OnRail++;
        }
        else if (Input.GetKeyDown("a") && OnRail > 1)
        {
            tf.Translate(-5.4f, 0f, 0f);
            OnRail--;
        }
    }

    void FixedUpdate ()
    {
        if (Travel)
        {
            rb.velocity = new Vector3(0, 0, speed * Time.deltaTime);
        }

        if (Input.GetKeyDown("space") && Grounded)
        {
            Grounded = false;
            rb.AddForce(new Vector3(0, 500000f * Time.deltaTime, 0));

        }

        if ((tf.position.y == 2f || tf.position.y == 10f) && rb.velocity.y == 0 && !Grounded)
        {
            Grounded = true;
        }
    }
}

The player is supposed to jump into the air, but only jumps almost no distance. The 2 and 10 Y positions are preset floors (I really don't need these 2 Y-coordinates. unless someone has a substitution for floor detection).


Solution

  • This is because GetKeyDown only occurs for one frame, meaning you are only applying a force upwards for that single frame. Additionally, Time.deltaTime is the amount of time it took to complete the last frame (a very small value), meaning you are applying a very small force upward. If you only want a single force applied on spacebar, there is no need to use Time.deltaTime here. Just do:

    rb.AddForce(Vector3.up * 100f); // or some other reasonable multipliier