我遇到了无限跳跃到空中的问题

im getting a problem with infinite jumps into the air

我实际上在这一点上失去了理智,过去 3 天一直遇到这个问题,想不出任何解决方案,这听起来可能很懒惰,但如果你能解决我的代码问题 那太好了,因为我不想失去更多的理智,在此先感谢

代码:

public class 玩家动作:MonoBehaviour {

public CharacterController controller;

public float speed = 12f;

Vector3 velocity;

public float gravity = -9.81f;

public Transform groundCheck;

public float groundDistance = 0.4f;

public LayerMask groundMask;

bool isGrounded;

public float jumpHeight = 3f;

void Start() 
{ 
 isGrounded = true;

}

// Update is called once per frame
void FixedUpdate()
{
     isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

     if (isGrounded && velocity.y < 0)
     {
         velocity.y = -2f;
     }
     
    float x = Input.GetAxis("Horizontal");
    float z = Input.GetAxis("Vertical");

    Vector3 move = transform.right * x + transform.forward * z;

    controller.Move(move * speed * Time.deltaTime);

    if (Input.GetKeyDown("space"))
    {
      velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
    
    }
       
    if (Input.GetKeyDown("space"))
    {
        isGrounded = false;
    }

    if ()
    {
        
    }


    velocity.y += gravity * Time.deltaTime;
    controller.Move(velocity * Time.deltaTime);


}

}

当您按下 space 时,您正在强制 isGrounded 为 false,尝试删除它,但实际上您并没有检查 isGrounded 以执行跳转。这是创可贴

    if (Input.GetKeyDown("space"))
    {
      if (isGrounded){
      velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
      } else return;
    
    }