Detailed explanation of Unity Bound

The content will be continuously updated, please correct me if there are any errors, thank you!
 

Detailed explanation of Unity Bound
     
TechX insists on bringing innovative technology to the world!

Have a better learning experience - keep working hard, keep improving, keep exploring
TechX ——Heart for exploration and heart for progress!

Helps master Bounds

quickly , saving valuable learning time for beginners and avoiding confusion!


Insert image description here



1. Overview of Bounds

1. Bounds type


In Unity, a bounding box is a geometric shape used to approximately represent the range or boundary of an object or a group of objects in three-dimensional space. It is a simple shape, usually a cube or rectangle, that completely surrounds an object or group of objects.

There are many types of bounding boxes, including:

  • AABB (Axis-Aligned Bounding Box): This is a bounding box oriented with the coordinate axis, and its six faces are parallel to the coordinate axis. AABB is very efficient at handling object collision detection, object visibility checking, and simple object bounding optimization.

  • OBB (Oriented Bounding Box): This is a bounding box that can rotate along the direction of the object. Unlike AABB, OBB can rotate freely depending on the object's orientation and therefore surrounds the object more accurately, but is also more computationally intensive.

  • Sphere Bounds: This is a sphere that surrounds an object, often used for collision detection or visibility checking of objects. A spherical bounding box may not be the most accurate representation for irregularly shaped objects, but it provides a simple and fast method of collision detection.

2. Bounds attribute


In Unity, many objects have a Bounds property that describes the bounding box of the object. For example, components such as Renderer, Collider, and Mesh all have Bounds properties, which are used to represent objects or bounding boxes for objects. The properties of Bounds usually include the center point position and size of the bounding box.

Insert image description here

size The dimensions of the bounding box, which describe the width, height, and depth of the bounding box along three axes (X, Y, and Z).
center The center point position of the bounding box. This center point is the geometric center of the object or object contained in the bounding box.
extents Represents half the size attribute, which represents the forward half size of the bounding box on each axis.
min (World coordinates) The smallest point of the bounding box. This value is always equal to center-extents.
max (World coordinates) The maximum point of the bounding box. This value is always equal to center+extents.
ClosestPoint(Vector3 point) Used to find the closest point to a given point on the bounding box. Pass in the Vector3 coordinates of a point and return the coordinates of the point closest to the point on the bounding box.
Contains(Vector3 point) Checks whether a point is inside the bounding box. Pass in a point represented by Vector3 coordinates. If the point is inside the bounding box, return true; otherwise, return false.
Encapsulate(Bounds bounds) Used to extend the bounding box to contain another Bounds object. Passing in a Bounds object, this method will adjust the current bounding box so that it completely contains the passed Bounds object.
Encapsulate(Vector3 point) Used to extend the bounding box to include a given point. Pass in the Vector3 coordinates of a point that will be completely contained by the bounding box.
SetMinMax(Vector3 min, Vector3 max) Sets the bounding box based on the coordinates of the minimum and maximum vertices. Pass in the coordinate Vector3 values ​​of the minimum and maximum vertices to redefine the position and size of the bounding box.
Expand(float amount) Adjusts the size of the bounding box by extending its dimensions on each axis. Passing in a floating point amount, this value will be added to the width, height and depth of the bounding box respectively.

2. Bounds in Unity

1. Renderer Bounds (renderer bounding box)


Renderer is a component that renders graphics to the screen. Each Renderer has a Bounds property, which represents the bounding box of the content rendered by the renderer. The bounding box is surrounded by the merger of all rendered meshes (Mesh) under this Renderer. Commonly used to determine the visibility of objects for camera cropping.

Draw Renderer Bounds:

public class MyComponent : MonoBehaviour
{
    
    
	//Renderer Bounds为世界坐标
    private Bounds bounds;
	private MeshRenderer renderer;

    void OnDrawGizmos()
    {
    
    
        // 获取物体的 MeshRenderer 组件
        renderer = GetComponent<MeshRenderer>();
        bounds = renderer.bounds;
        
        // 设置 Gizmos 的颜色
        Gizmos.color = Color.green;
        Gizmos.DrawWireCube(bounds.center, bounds.size);
    }
}
  • The effect of displacement on Render Bounds:

When the object is displaced, the renderer's Bounds will be updated accordingly to follow the movement of the object. At this point, the renderer's Bounds will also move to ensure correct visibility calculations.

Insert image description here

  • The effect of rotation on Render Bounds:

When the object rotates, the renderer's Bounds will be updated accordingly. Unlike displacement, rotation causes the size of the bounding box to change, but it does not rotate as the object rotates.

Insert image description here

  • The effect of scaling on Render Bounds:

When the object is scaled, the renderer's Bounds will be updated accordingly according to the scale. At this time, the renderer's Bounds will also be scaled to ensure the correct bounding box.

Insert image description here

2. Collider Bounds (collider bounding box)


Collider is a component used to detect collisions. Various types of colliders (such as BoxCollider, SphereCollider, etc.) have a Bounds property, which represents the bounding box of the collider. This bounding box is used to calculate collisions, trigger collision events or perform physics simulations.

Draw Collider Bounds:

public class MyComponent : MonoBehaviour
{
    
    
	//Collider Bounds为世界坐标
    private Bounds bounds;
	private BoxCollider boxCollider;

    void OnDrawGizmos()
    {
    
    
         //获取物体的 BoxCollider组件
         boxCollider = GetComponent<BoxCollider>();
         bounds = boxCollider.bounds;
        
        // 设置 Gizmos 的颜色
        Gizmos.color = Color.green;
        Gizmos.DrawWireCube(bounds.center, bounds.size);
    }
}
  • The effect of displacement on Collider Bounds:

When the object is displaced, the renderer's Bounds will be updated accordingly to follow the movement of the object. At this point, the renderer's Bounds will also move to ensure correct visibility calculations.

Insert image description here

  • The effect of rotation on Collider Bounds:

When the object rotates, the renderer's Bounds will be updated accordingly. Unlike displacement, rotation causes the size of the bounding box to change, but it does not rotate as the object rotates.

Insert image description here

  • Effect of scaling on Collider Bounds:

When the object is scaled, the renderer's Bounds will be updated accordingly according to the scale. At this time, the renderer's Bounds will also be scaled to ensure the correct bounding box.

Insert image description here

3. Mesh Bounds (grid bounding box)


Mesh is a collection that represents the surface of a three-dimensional object, and MeshRenderer is used to render these Mesh. Each Mesh also has a Bounds property, which represents the bounding box of the mesh. This bounding box is usually the smallest bounding box calculated from the vertex positions of the mesh and is used to optimize rendering and collision detection.

Draw Mesh Bounds:

public class MyComponent : MonoBehaviour
{
    
    
	//Mesh Bounds为本地坐标
    private Bounds bounds;
	private MeshFilter filter ;

    void OnDrawGizmos()
    {
    
    
          获取物体的 MeshFilter组件
         MeshFilter filter = GetComponent<MeshFilter>();
         bounds = filter.sharedMesh.bounds;
         //将本地坐标转换未为世界坐标
         var centerPoint = transform.TransformPoint(bounds.center);
         bounds = new Bounds(centerPoint, bounds.size);
        
        // 设置 Gizmos 的颜色
        Gizmos.color = Color.green;
        Gizmos.DrawWireCube(bounds.center, bounds.size);
    }
}
  • The effect of displacement on Mesh Bounds:

When the object is displaced, the renderer's Bounds will be updated accordingly to follow the movement of the object. At this point, the renderer's Bounds will also move to ensure correct visibility calculations.

Insert image description here

  • The effect of rotation on Collider Bounds:
  • Effect of scaling on Collider Bounds:

The Bounds of a Mesh are the smallest bounding boxes calculated based on the positions of its vertices when the Mesh is created. This bounding box is usually fixed when the Mesh is created and does not update in real time as the object scales or rotates.

Therefore, when the object is scaled or rotated, the Mesh Bounds will not update in real time to adapt to these changes. Mesh Bounds maintain the original calculated bounding box shape and size even if the object is scaled or rotated.

Insert image description here
Insert image description here

3. The difference between Bounds and Collider


  • Bounding box (OBB) in Collider:

Collider components usually create corresponding collision areas based on the shape of the object (for example, BoxCollider, SphereCollider, etc.). The bounding boxes used by these Colliders are usually oriented bounding boxes (OBB), that is, they can rotate with the rotation of the object and form corresponding collision areas according to the shape of the object.

OBB provides better detection accuracy because it can better adapt to the shape and rotation of objects.

public class MyComponent : MonoBehaviour
{
    
    
	private BoxCollider boxCollider;

    void OnDrawGizmos()
    {
    
    
         //获取物体的 BoxCollider组件
         boxCollider = GetComponent<BoxCollider>();
         
         // 设置 Gizmos 的颜色
         Gizmos.color = Color.green;
         Matrix4x4 rotationMatrix = Matrix4x4.TRS(transform.position, transform.rotation, transform.lossyScale);
         // 根据物体的变换,绘制实时的 Bounds
         Matrix4x4 oldMatrix = Gizmos.matrix;
         Gizmos.matrix = rotationMatrix;
         Gizmos.DrawWireCube(boxCollider.center, boxCollider.size);
         Gizmos.matrix = oldMatrix;
    }
}
  • Bounding box (AABB) in Bounds:

Bounds Bounding boxes are usually undirected bounding boxes (AABB). This means that it does not rotate as the object rotates, but always remains oriented along the coordinate axis.

AABB is often used to quickly wrap an object, but may not wrap the object's shape accurately when the object is rotated because it is a fixed bounding box along the coordinate axis.


4. Related calculations of Bounds

1. Calculate Bounds vertices

/// <summary> Bounds顶点 </summary>
/// <param name="bounds"></param>
public Vector3[] DrawBoundBoxLine(Bounds bounds)
{
    
    
    //计算出包围盒8个点
    Vector3 min = bounds.min;
    Vector3 max = bounds.max;
    Vector3[] vertices = new Vector3[8];

    // 计算八个顶点的坐标
    vertices[0] = new Vector3(min.x, min.y, min.z);
    vertices[1] = new Vector3(max.x, min.y, min.z);
    vertices[2] = new Vector3(min.x, min.y, max.z);
    vertices[3] = new Vector3(max.x, min.y, max.z);
    vertices[4] = new Vector3(min.x, max.y, min.z);
    vertices[5] = new Vector3(max.x, max.y, min.z);
    vertices[6] = new Vector3(min.x, max.y, max.z);
    vertices[7] = new Vector3(max.x, max.y, max.z);
	return vertices;
}

2. Expand multiple Bounds

public class MyComponent : MonoBehaviour
{
    
    
	private Bounds bounds;
	
	/// <summary> 扩展Bounds </summary>
	/// <param name="model"></param>
	public Bounds ExtendBound(Transform model)
	{
    
    
		Vector3 center = Vector3.zero;
		Renderer[] renders = model.GetComponentsInChildren<Renderer>();
		
		foreach (Renderer child in renders){
    
    
			center += child.bounds.center;   
		}
		
		center /= model.GetComponentsInChildren<Transform>().Length; 
		Bounds bounds = new Bounds(center,Vector3.zero);
		
		foreach (Renderer child in renders)
		{
    
    
			bounds.Encapsulate(child.bounds);   
		}
		return bounds;
	}
	
	void OnDrawGizmos()
	{
    
    
	    bounds = ExtendBound(transform);
	     设置 Gizmos 的颜色
	    Gizmos.color = Color.green;
	    Gizmos.DrawWireCube(bounds.center, bounds.size);
	}
}




TechX ——Heart for exploration and heart for progress!

Every fall is a growth,

every effort is a progress

END
Thank you for reading this blog! Hope this content is helpful to you. If you have any questions or comments, or would like to know more about this topic, please feel free to leave a message in the comment area to communicate with me. I will be more than happy to discuss and share more interesting content with you all.
If you like this blog, please like and share it with more friends so that more people can benefit. In the meantime, you can also follow my blog to get the latest updates and articles in a timely manner.
In future writing, I will continue to work hard to share more interesting and practical content. Thank you again for your support and encouragement, and I look forward to seeing you in the next blog!

Supongo que te gusta

Origin blog.csdn.net/caiprogram123/article/details/135441086
Recomendado
Clasificación