前言,公司项目要实现门窗的挖洞效果。比来比去使用了CSG,很方便就一个dll
链接:https://pan.baidu.com/s/1W0uRa6outkDAvyUdp6HqXg
提取码:i7dw
最最根本的代码也很简单
/// <summary>
/// 最根本的挖洞方法
/// </summary>
/// <param name="target">被挖洞的物体</param>
/// <param name="brush">去挖洞的物体</param>
/// <param name="isPlane">被挖物体是否是平面</param>
/// <returns></returns>
protected GameObject PotholMethod(GameObject target, GameObject brush, bool isPlane)
{
//不能直接new gameobject后添加meshfilter,否则可能挂不上meshfilter很坑,查了很久
GameObject CSGGo = GameObject.Instantiate(target);
try
{
//csg创建出挖洞完的物体
Mesh mesh = CSG.Subtract(target, brush, isPlane, true);
if (mesh != null)
{
MeshRenderer meshRenderer = CSGGo.GetComponent<MeshRenderer>();
MeshFilter meshFilter = CSGGo.GetComponent<MeshFilter>();
meshFilter.sharedMesh = mesh;
//将mesh和材质付给新物体
meshRenderer.material = target.GetComponent<MeshRenderer>().material;
}
else
{
Debug.Log(target.name + "挖洞出现mesh为空的物体");
}
}
catch (System.Exception e)
{
Debug.Log(e.Message);
}
return CSGGo;
}
本来测试的时候没有什么问题,可以很开心的挖洞,直到设计师画了一个斜的墙体,总是 有时候报错Error During CSG Operation,有时候不报错,好吧还是dll内部问题,我就想着既然是斜墙有问题,那么在挖洞的时候把这面墙给弄成没有角度在挖洞。思考ing
笔记结于2023.3.16
好吧,晚上原因找到了,之前墙面用mesh算法算的,如果用unity自带的plane,挖起来没有报错,后来改进了创建mesh的算法,不能用只有四个点形成plane的算法,改进后plane的mesh顶点长宽各10个,就没问题了。