Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unity make player only jump when it's grounded

I recently started messing around in Unity and I’m trying to make a 2D platformer game. I tried making it so that my player is only able to jump when it is grounded and this is the code I came up with, but it isn’t working for some reason and I don’t understand why.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour
{
    public float moveSpeed = 5;
    public float jumpSpeed =  5;
    public Rigidbody2D rb;
    public GameObject gameObject;
    bool isGrounded;
    Vector3 movement;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (isGrounded)
        {
            Jump();
        } else
        {
            // do nothing
        }
        Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
        transform.position += movement * Time.deltaTime * moveSpeed;
    }

    void Jump()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            rb.AddForce(new Vector2(0f, jumpSpeed), ForceMode2D.Impulse);
        }
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.gameObject.CompareTag("Ground"))
        {
            isGrounded = true;
        } else
        {
            isGrounded = false;
        }
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Instead of having the else { isGrounded = false;} inside of your collision check, add isGrounded = false; inside of your Jump() function so that you’re guaranteed to only be able to jump while you’re on the ground;
Additionally you could have Jump(); without the if statement in your Update() function and have it inside Jump() like this if (isGrounded && Input.GetKeyDown(KeyCode.Space))

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading