"void OnCollisionStay()" 运行不正常?

"void OnCollisionStay()" not functioning properly?

我在 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;

它总是表明我没有统一,所以当我按 space 时没有任何反应,我没有收到任何错误或任何东西。我认为问题可能出在 void OnCollisionStay() 部分,在此先感谢任何可以提供帮助的人。

如果场景加载前已经发生碰撞,方法OnCollisionStay()将不会被触发。您需要将 isGrounded 的默认值默认设置为 true 或在初始化时间(Awake/Start)的任何位置设置它。

无论哪种方式,您的代码中都缺少某些东西,您的 Jump if 语句缺少大括号。

        //jumping
        if (Input.GetKeyDown(KeyCode.Space) && isGrounded) 
            rb.AddForce(jump * jumpForce, ForceMode.Impulse); // this is executed if the statement is true
        isGrounded = false; // THIS IS ALWAYS EXECUTED

固定码:

  //jumping
    if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
    {
        rb.AddForce(jump * jumpForce, ForceMode.Impulse);
        isGrounded = false;
    }

Good reference to check regarding order of execution.

Guide regarding OnTriggerStay

简单,使用内置的 CharacterController 属性 controller.isGrounded 其中 return True/False.

if (Input.GetKeyDown(KeyCode.Space) && controller.isGrounded)

rb.AddForce(jump * jumpForce, ForceMode.Impulse);

所以,不再需要使用 isGrounded = false