Unity Raycast 总是返回 true

Unity Raycast always returning true

我在 Unity 中有一个角色,我正在使用光线投射让他跳跃。但即使光线投射没有击中地面(我可以在调试输出中看到光线)玩家仍然可以跳跃。任何想法为什么射线总是认为它正在碰撞?光线会不会击中我的角色对撞机,使它成为真实的?我在网上搜索了几个小时,但没有找到解决问题的方法。这是我的代码:

void FixedUpdate()
{
    Ray ray = new Ray();
    RaycastHit hit;
    ray.origin = transform.position;
    ray.direction = Vector3.down;
    bool output = Physics.Raycast(ray, out hit);
    Debug.DrawRay(ray.origin, ray.direction, Color.red);
    if (Input.GetKey(KeyCode.Space) && output)
    {
        r.AddForce(Vector3.up * 1f, ForceMode.VelocityChange);

    }

}

Could the ray be hitting my character collider?

是的,这是可能的。

这个问题其实很容易用Debug.Log解决。

Debug.Log("Ray Hit: " + hit.transform.name); 放在 if 语句中,它将显示什么对象正在阻塞 Raycast

如果这确实是问题所在, post 介绍了多种修复方法。该答案和代码略有变化,因为这个问题是关于 3D 而不是 2D。只需使用层。将您的播放器置于第 9 层,然后问题就会消失。

void FixedUpdate()
{
    int playerLayer = 9;

    //Exclude layer 9
    int layerMask = ~(1 << playerLayer); 


    Ray ray = new Ray();
    RaycastHit hit;
    ray.origin = transform.position;
    ray.direction = Vector3.down;
    bool output = Physics.Raycast(ray, out hit, 100f, layerMask);



    Debug.DrawRay(ray.origin, ray.direction, Color.red);
    if (Input.GetKey(KeyCode.Space) && output)
    {
        r.AddForce(Vector3.up * 1f, ForceMode.VelocityChange);
        Debug.Log("Ray Hit: " + hit.transform.name);
    }
}