【发布时间】:2022-01-09 09:15:36
【问题描述】:
我在 3d 游戏的跳转代码中遇到地面检测问题。我确定跳转脚本的其他部分可以正常工作,但我是 C# 编码的新手,所以我当然可能错了。
[RequireComponent(typeof(Rigidbody))]
public class Movement : MonoBehaviour{
public CharacterController controller;
public float speed = 12f;
//inputs
float x, z;
public bool isGrounded;
//jump
public Vector3 jump;
public float jumpForce = 400;
Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
jump = new Vector3(0.0f, 2.0f, 0.0f);
}
void OnCollisionStay()
{
isGrounded = true;
}
// Update is called once per frame
void Update()
{
//walking n stuff
x = Input.GetAxis("Horizontal");
z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
transform.position += move * Time.deltaTime * speed;
controller.Move(move * speed * Time.deltaTime);
//jumping
if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
rb.AddForce(jump * jumpForce, ForceMode.Impulse);
isGrounded = false;
它总是表明我没有以团结为基础,因此当我按下空格时什么都没有发生,我没有得到任何错误或任何东西。我认为问题可能是无效的 OnCollisionStay() 部分,提前感谢任何可以提供帮助的人。
【问题讨论】:
-
尝试将
isGrounded的默认值设置为true。从快速的谷歌搜索来看,在我看来OnCollisionStay是在碰撞点运行的,所以如果你在启动时已经在地面上,它可能不会触发。 -
与问题无关,但我建议使用 Unity 的新输入系统