美文网首页
unity将选中的预制体对齐到下方任意物体表面

unity将选中的预制体对齐到下方任意物体表面

作者: Rayson | 来源:发表于2025-04-08 14:25 被阅读0次
using UnityEngine;
using UnityEditor;

public class AlignToSurface : MonoBehaviour
{
    [MenuItem("Tools/将选中的预制体贴合表面")]
    static void AlignSelectedObjectsToSurface()
    {
        foreach (GameObject obj in Selection.gameObjects)
        {
            Vector3 origin = obj.transform.position + Vector3.up * 100f; // 向上偏移,确保从上往下检测
            Ray ray = new Ray(origin, Vector3.down);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, 1000f))
            {
                // 对齐到碰撞点
                Vector3 newPos = hit.point;

                // 如果你希望物体底部落地而不是中心,可以加上模型高度的一半(比如通过 Renderer.bounds)
                Renderer renderer = obj.GetComponentInChildren<Renderer>();
                if (renderer != null)
                {
                    float bottomOffset = obj.transform.position.y - renderer.bounds.min.y;
                    newPos.y += bottomOffset;
                }

                obj.transform.position = newPos;

                Debug.Log($"{obj.name} 已贴合表面:{hit.collider.name}");
            }
            else
            {
                Debug.LogWarning($"{obj.name} 下方未检测到物体表面");
            }
        }
    }
}


在场景中选择一个或多个悬空的预制体。

在 Unity 菜单栏点击:
Tools > 将选中的物体落地

相关文章

网友评论

      本文标题:unity将选中的预制体对齐到下方任意物体表面

      本文链接:https://www.haomeiwen.com/subject/tastbjtx.html