Home > Enterprise >  Unity make player only jump when it's grounded
Unity make player only jump when it's grounded

Time:04-14

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;
        }
    }
}

CodePudding user response:

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))

CodePudding user response:

you can use OnCollisionExit2D(Collision2D Collider) {} to set isgrounded to false. It would look like something like this:

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

private void OnCollisionEnter2D(Collision2D collision)
{
    if(collision.tag == "Ground")
    {
        isGrounded = true;
    }
}
void OnCollisionExit2D(Collision2D Collider)
{
    if (Collider.tag == "Ground")
    {
        isGrounded = false;
    }
}




              
                      
  • Related