jumping in this basic platformer script isn't working for me

46 views Asked by At

I'm trying to make a basic platformer script, but when I come to the Jump() method, it activates, but doesn't jump!

Here's my platformer code (Removed the horizontal movement, due to stack not allowing to paste all my code in) :

public class Player : MonoBehaviour
{
   
    new private Rigidbody rigidbody;
    public GameObject player;
    [Range(1,10)]
    public float jumpHeight = 5.0f;
    private bool isOnGround;


    // Start is called before the first frame update
    void Start()
    {
        player = GetComponent<GameObject>();
        rigidbody = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        


        
        if(Input.GetButtonDown("Jump") && isOnGround)
        {
            Debug.Log("Space was pressed");
            jump();
            isOnGround = false;

        }

    }


    private void jump()
    {
        
        Debug.Log("Jump was activated");
        rigidbody.AddForce(player.transform.up * jumpHeight * Time.deltaTime, ForceMode.Impulse);
        
    }
    private void OnCollisionEnter(Collision collision)
    {
        if(collision.gameObject.tag.Equals("Ground"))
        {
            isOnGround = true;
        }
    }

}

tried many fixes, even did my code on a separate computer, sorry if this looks confusing, new to stack overflow.

1

There are 1 answers

2
AudioBubble On

The code is fine, however i reccomend you use compareTag instead:

private void OnCollisionEnter(Collision collision)
{
    if(collision.gameObject.CompareTag("Ground"))
    {
        isOnGround = true;
    }
}

also you can make the isOnGround variable public to see it in the inspector. That way you can make sure its being set correctly, alternatively you can use Debug.Log(isOnGround) which will help find your issue. For issues like this, i generally just make all related private variables public, so i can see if something isnt being set correctly.

EDIT: also you DEFINATELY dont want to multiply your jump by deltaTime, deltaTime is for constant movements, whereas your just applying a single force.