【问题标题】:"void OnCollisionStay()" not functioning properly?“void OnCollisionStay()”不能正常工作?
【发布时间】: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 的新输入系统

标签: c# unity3d 3d collision


【解决方案1】:

如果在场景加载之前已经发生碰撞,则不会触发方法OnCollisionStay()。您需要将isGrounded的默认值默认设置为true或在初始化时间(唤醒/启动)的任何地方设置。

无论哪种方式,您的代码中都缺少某些内容,您的 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

【讨论】:

    【解决方案2】:

    简单,使用您的 CharacterController 内置属性 controller.isGrounded 返回 True/False。

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

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

    所以,不用再使用isGrounded = false

    【讨论】:

      猜你喜欢
      • 2012-05-19
      • 2013-03-30
      • 2010-11-30
      • 2021-10-02
      • 2017-08-06
      • 2013-11-22
      • 1970-01-01
      • 2013-09-10
      • 2017-04-05
      相关资源
      最近更新 更多