Unity让玩家只有在接地时才会跳跃

Unity make player only jump when it's grounded

我最近开始在 Unity 中闲逛,我正在尝试制作一款 2D 平台游戏。我试着让我的播放器只有在接地时才能跳跃,这是我想出的代码,但由于某种原因它不起作用,我不明白为什么。

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

不要在你的碰撞检查中添加 else { isGrounded = false;},而是在你的 Jump() 函数中添加 isGrounded = false;在地面上; 此外,您可以在 Update() 函数中没有 if 语句的 Jump(); 并像这样 inside Jump() if (isGrounded && Input.GetKeyDown(KeyCode.Space))

您可以使用 OnCollisionExit2D(Collision2D Collider) {}isgrounded 设置为 false。它看起来像这样:

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