Home > Back-end >  Unable to jump in Unity2D
Unable to jump in Unity2D

Time:12-11

I can't jump when I press the up arrow key. When I remove the condition of isGrounded to be able to jump, then my character can jump while in the air.

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

public class PlayerMovement : MonoBehaviour
{
    [SerializeField] private float speed;
    private Rigidbody2D body;
    bool isGrounded;

    private void Awake()
    {
        body = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        float HorizontalInput = Input.GetAxis("Horizontal");
        body.velocity = new Vector3(Input.GetAxis("Horizontal") * speed, body.velocity.y);

        if (HorizontalInput < -0.01f)
            transform.localScale = Vector3.one;
        else if (HorizontalInput > 0.01f)
            transform.localScale = new Vector3(-1, 1, 1);
        
        if (Input.GetKey(KeyCode.UpArrow))
            isGrounded = false;

        if (Input.GetKey(KeyCode.UpArrow) && isGrounded)
            body.velocity = new Vector2(body.velocity.x, speed);
    }

    private void OnCollisionEnter2D()
    {
        isGrounded = true;
    }
}

I tried to use OnCollisionEnter2D to set isGrounded to true, but I don't think it is working.

CodePudding user response:

The problem is with this logic:

        if (Input.GetKey(KeyCode.UpArrow))
            isGrounded = false;

        // isGrounded will always be false here if up-arrow key is pressed.
        if (Input.GetKey(KeyCode.UpArrow) && isGrounded)
            body.velocity = new Vector2(body.velocity.x, speed);

What you are looking for:

        if (Input.GetKey(KeyCode.UpArrow) && isGrounded) {
            body.velocity = new Vector2(body.velocity.x, speed);
            isGrounded = false;
        }

Use curly braces to denote multiple lines of code under a statement.

Also, use FixedUpdate for physics related manipulation like Rigidbodies.

  • Related