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

Unity3D中如何让Raycast在命中物体前提前停止 解决方块放置穿模

问题核心原因

你当前直接用射线命中点生成方块,命中点本身位于已有方块的表面,生成的新方块会直接和已有方块重叠,且你编写的网格吸附逻辑没有实际调用,是偏移、穿模的主要诱因。不需要修改射线的检测停止逻辑,通过命中法线计算放置位置+调用网格吸附即可解决问题。

修改后的代码实现

1. 射线检测放置逻辑

if (Input.GetMouseButtonDown(0))
{
    RaycastHit hit;
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    //Make Whatever a Raycast layer or if you don't want it just exclude it
    if (Physics.Raycast(ray, out hit, Whatever.value))
    {
        // 沿命中法线方向偏移半个方块边长,避免和被命中的方块重叠
        // 方块边长为1单位时取0.5,其他尺寸替换为对应边长的一半即可
        Vector3 placePos = hit.point + hit.normal * 0.5f;
        // 调用网格吸附逻辑校准坐标
        placePos = SnapToGrid(placePos);
        Instantiate(stoneBricks, placePos, UnityEngine.Quaternion.identity);
    }
}

2. 优化后的网格吸附逻辑

// 按方块网格校准坐标,gridSize为单个方块的边长,默认1单位
Vector3 SnapToGrid(Vector3 rawPos, float gridSize = 1f)
{
    return new Vector3(
        Mathf.Round(rawPos.x / gridSize) * gridSize,
        Mathf.Round(rawPos.y / gridSize) * gridSize,
        Mathf.Round(rawPos.z / gridSize) * gridSize
    );
}

适配调整说明

  • 如果你的方块预制体锚点在左下角而非模型中心,将法线偏移量改为1 * gridSize,吸附逻辑里的Mathf.Round替换为Mathf.Floor即可
  • 可在生成方块前额外增加一步碰撞检测,确认吸附后的坐标没有已生成的方块,避免重复放置导致穿模

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 02:39:02