角色停止移动,我不知道为什么



我的代码运行得很好——角色左右移动并跳跃,但我试图让他停止跳跃两次,他只是完全停止了移动。你能帮我弄清楚我做错了什么吗?我已经查过这个问题,但还没有找到一个对我来说有意义的答案(我相对较新(,所以如果有人能和我一起解决这个问题,我会非常感激,这样我就可以重新开始工作学习了。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
bool jumpKeyWasPressed;
float horizontalInput;
Rigidbody rigidBodyComponent;
bool isGrounded;
// Start is called before the first frame update
void Start()
{
rigidBodyComponent = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
//Space key input
if (Input.GetKeyDown(KeyCode.Space))
{
jumpKeyWasPressed = true;   
}
horizontalInput = Input.GetAxis("Horizontal");
}
//main problem I think
void FixedUpdate ()
{
if (!isGrounded)
{
return;
}
if (jumpKeyWasPressed)
{
rigidBodyComponent.AddForce(Vector3.up * 5, ForceMode.VelocityChange);
jumpKeyWasPressed = false;
}
rigidBodyComponent.velocity = new Vector3(horizontalInput,rigidBodyComponent.velocity.y, 0);
}

void OnCollisionEnter(Collision collision)
{
isGrounded = true;
}
void OnCollisionExit(Collision collision)
{
isGrounded = false;
}
}

如果isGrounded为false,则直接从函数中return。最后一行也以这种方式跳过。要解决此问题,只需检查isGrounded是否为true,然后只执行跳转代码(忘记return(。

if (isGrounded) {
if (jumpKeyWasPressed) {
// ...
}
}

相关内容

最新更新