isGrounded 无法正常工作会导致双跳

isGrounded not working properly gives double jump

我试图让我的立方体在我按下 space 时跳跃。但由于某种原因,isGrounded 出现故障,即使它在空中我也可以二段跳。而且它非常不一致,就像如果我发送垃圾邮件 space 一点它跳得更高或开始旋转立方体。我是团结的初学者,不知道为什么。任何帮助表示赞赏。

我试过使用 rb.addForce 而不是 transform.Translate 但是当我移动它时它开始旋转立方体并且我希望它在平台上平滑滑动。

我的代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
 
public class PlayerController : MonoBehaviour
{
 
    private Rigidbody rb;
 
    public Vector3 jump;
    public float jumpForce = 2.0f;
    public bool isGrounded;
 
    public float speed = 0;
    private float movementX;
    private float movementY;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        jump = new Vector3(0.0f, 2.0f, 0.0f);
    }
 
    void OnMove(InputValue movementValue)
    {
        Vector2 movementVector = movementValue.Get<Vector2>();
        movementX = movementVector.x;
        movementY = movementVector.y;
    }
 
    void OnCollisionStay()
    {
        isGrounded = true;
        Debug.Log("GROUDED");
    }
 
    private void Update()
    {
        if (Keyboard.current.spaceKey.wasPressedThisFrame && isGrounded)
        {
            rb.AddForce(jump * jumpForce, ForceMode.Impulse);
            isGrounded = false;
            Debug.Log("UnGROUNDED");
        }
    }
 
    private void FixedUpdate()
    {
        Vector3 movement = new Vector3(movementX, 0.0f, movementY);
        transform.Translate(movement/speed);
    }
}

同时添加 void OnCollisionExit:

    private void OnCollisionExit(Collision collision)
    {
        isGrounded = false;
        Debug.Log("UnGROUNDED");
    }

从更新中,您可以删除

isGrounded = false;
Debug.Log("UnGROUNDED");

要防止立方体旋转,请选中刚体中“约束”部分中的“冻结旋转”框: