You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中RaycastHit.Point表现异常问题求助

问题排查与解决

1. 层掩码(LayerMask)使用错误

这是最常见的问题:Physics.Raycast的layerMask参数需要的是层掩码(整数位掩码),而非层索引。如果你的floorLayer是通过LayerMask.NameToLayer("Floor")获取的层索引(比如返回2),直接传入会导致Raycast无法正确识别目标层,进而无法命中地面。

修改代码:

public Vector3 MouseToWorldPositions()
{
    Ray ray = playerCam.ScreenPointToRay(Input.mousePosition);
    // 正确生成地面层的掩码
    int floorMask = 1 << floorLayer;
    if (Physics.Raycast(ray, out RaycastHit hit, 999f, floorMask))
    {
        return hit.point;
    }
    else
    {
        Debug.LogWarning("Raycast未命中地面层");
        // 可选:返回射线最远端点,避免物体跳转到原点
        return ray.GetPoint(999f);
    }
}

2. 地面缺少碰撞体

确保你的地面GameObject上添加了Collider组件(如BoxCollider、MeshCollider),且未勾选Is Trigger(Trigger不会被常规Raycast检测到)。

3. PlayerCam未正确赋值

检查playerCam变量是否在Inspector面板中拖入了正确的相机对象,也可以通过代码自动赋值:

void Awake()
{
    if (playerCam == null)
        playerCam = Camera.main;
}

4. 调试验证

添加调试代码,直观确认Raycast状态:

public Vector3 MouseToWorldPositions()
{
    Ray ray = playerCam.ScreenPointToRay(Input.mousePosition);
    int floorMask = 1 << floorLayer;
    if (Physics.Raycast(ray, out RaycastHit hit, 999f, floorMask))
    {
        // Scene视图中绘制绿色射线表示命中
        Debug.DrawLine(ray.origin, hit.point, Color.green);
        Debug.Log($"命中位置:{hit.point}");
        return hit.point;
    }
    else
    {
        // Scene视图中绘制红色射线表示未命中
        Debug.DrawLine(ray.origin, ray.GetPoint(999f), Color.red);
        Debug.LogWarning("未命中地面");
        return ray.GetPoint(999f);
    }
}

内容的提问来源于stack exchange,提问作者Emirhan Soylu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 19:48:04