序
比如,目前导入了一个obj文件,想知道它的AABB包围盒是什么。
官方文档
Unity - Scripting API: Bounds (unity3d.com)
可以看到,包围盒有三个类别的:
Mesh.bounds
Unity - Scripting API: Mesh.bounds (unity3d.com)
不随gameobject的几何变换而变换,大概是直接用obj里的顶点坐标算出来的;也就是所谓的模型坐标系。
api怎么调用的?主要就是这几句:
试一试
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoundTest : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Mesh mesh = GetComponent<MeshFilter>().mesh;
Bounds bounds = mesh.bounds;
print(bounds.center); // 把文档里的属性,都打印出来看看
print(bounds.size);
print(bounds.min);
print(bounds.max);
print(bounds.extents);
}
// Update is called once per frame
void Update()
{
}
}
关于文档里面not change的演示:
代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoundTest : MonoBehaviour
{
private Mesh mesh;
private Bounds bounds;
// Start is called before the first frame update
void Start()
{
mesh = GetComponent<MeshFilter>().mesh;
// bounds = mesh.bounds; // 不能放到这里的,放在这里的话,每帧打印的都是同一个bounds;就算是rend.bounds,打印结果也不变
}
// Update is called once per frame
void Update()
{
bounds = mesh.bounds; // 应该实时获取
print(bounds.center);
}
}
结果:
Render.bounds
Unity - Scripting API: Renderer.bounds (unity3d.com)
主要是这么几句:
试一试
代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoundTest : MonoBehaviour
{
private Mesh mesh;
private Renderer rend;
private Bounds bounds;
// Start is called before the first frame update
void Start()
{
mesh = GetComponent<MeshFilter>().mesh;
rend = GetComponent<Renderer>();
}
// Update is called once per frame
void Update()
{
//bounds = mesh.bounds;
bounds = rend.bounds; // 实时获取包围盒,才能看到变没变
print(bounds.center);
}
}
后记
知道这些,其实就差不多了。
更详细的可以看这些:
(87条消息) Unity Bounds的理解_一梭键盘任平生的博客-CSDN博客
(87条消息) 【Unity3D】绘制物体外框线条盒子_unity 绘制线框_little_fat_sheep的博客-CSDN博客
总结的很好的: