Unity 获取复杂物体(模型)中心点
1.获取物体中心点
public Vector3 GetCenter(GameObject target)
{
Renderer[] mrs = target.gameObject.GetComponentsInChildren<Renderer>();
Vector3 center = target.transform.position;
if (mrs.Length != 0)
{
Bounds bounds = new Bounds(center, Vector3.zero);
foreach (Renderer mr in mrs)
{
bounds.Encapsulate(mr.bounds);
}
center = bounds.center;
}
return center;
}
2.获取物体包围盒(通过Renderer)
public Bounds GetBounds(GameObject target, bool include_children = true)
{
Renderer[] mrs = target.gameObject.GetComponentsInChildren<Renderer>();
Vector3 center = target.transform.position;
Bounds bounds = new Bounds(center, Vector3.zero);
if (include_children)
{
if (mrs.Length != 0)
{
foreach (Renderer mr in mrs)
{
bounds.Encapsulate(mr.bounds);
}
}
}
else
{
Renderer rend = target.GetComponentInChildren<Renderer>();
if (rend)
{
bounds = rend.bounds;
}
}
return bounds;
}
3.获取物体包围盒(通过MeshFilter)
public Bounds GetLocalBounds(GameObject target, bool include_children = true)
{
MeshFilter[] mfs = target.gameObject.GetComponentsInChildren<MeshFilter>();
Vector3 center = target.transform.localPosition;
Bounds bounds = new Bounds(center, Vector3.zero);
if (include_children)
{
if (mfs.Length != 0)
{
foreach (MeshFilter mf in mfs)
{
if (mf.mesh)
{
bounds.Encapsulate(mf.mesh.bounds);
}
}
}
}
else
{
MeshFilter mf = target.GetComponentInChildren<MeshFilter>();
if (mf && mf.mesh)
{
bounds = mf.mesh.bounds;
}
}
return bounds;
}
文章来源地址https://www.toymoban.com/news/detail-785612.html
文章来源:https://www.toymoban.com/news/detail-785612.html
到了这里,关于unity 获取复杂物体(模型)中心点的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!