Search Unity

  1. If you have experience with import & exporting custom (.unitypackage) packages, please help complete a survey (open until May 15, 2024).
    Dismiss Notice
  2. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice

Question bounds not following the shape of the object

Discussion in 'Scripting' started by thatwierdguy, Jan 24, 2023.

  1. thatwierdguy

    thatwierdguy

    Joined:
    Jan 18, 2022
    Posts:
    1
    I am working on a physics simulation, and am trying to "fill" objects with small spheres. I am using Collider.bounds.contains to make sure it fills the object. Instead of making the object out of the spheres, it follows a rectangular area around the object.
    Code (CSharp):
    1.         float x = obj_x;
    2.         float y = obj_y;
    3.         float z = obj_z;
    4.         Collider sape = GetComponent<Collider>();
    5.         x = sape.bounds.min.x;
    6.         y = sape.bounds.min.y;
    7.         z = sape.bounds.min.z;
    8.         bool ext = false;
    9.         while (ext == false)
    10.         {
    11.            
    12.             Pos = new Vector3(x, y, z);
    13.  
    14.             if (sape.bounds.Contains(Pos))
    15.             {
    16.                 Instantiate(particle, Pos, Quaternion.identity);
    17.             }
    18.             if (z >= sape.bounds.max.z)
    19.             {
    20.                 ext = true;
    21.             }else
    22.             if (y >= sape.bounds.max.y)
    23.             {
    24.                 y = sape.bounds.min.y;
    25.                 z += .1f;
    26.             }else
    27.             if (x >= sape.bounds.max.x)
    28.             {
    29.                 x = sape.bounds.min.x;
    30.                 y += .1f;          
    31.             }
    32.             x += .1f;
    33.  
    34.         }
     

    Attached Files:

  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,925
    Yes you have discovered what
    bounds
    actually is. Bounds are better known as AABBs or "Axis-Aligned Bounding Boxes". They look exactly like what your code is drawing. Boxes aligned on the world axes to facilitate the physics engine's collision broad phase. They are not meant to capture the actual shape of the collider.

    If you want to check if a given point is actually within the collider itself, you can do something like this:
    Code (CSharp):
    1. bool IsWithinCollider(Collider c, Vector3 point) {
    2.   return c.ClosestPoint(point) == point;
    3. }
    By combining your existing code with this function, you can draw only spheres that are within the collider itself.
     
    Last edited: Jan 25, 2023
    Bunny83 likes this.