- Home /
Fill an object's (probably mesh colliders) inside with smaller objects evenly
I am trying to make big shapes with small lot of cubes. For example reposition 500 cubes to form a hammer.
Normally I am filling colliders with this code
public static Vector3 RandomPointInBounds(Collider collider)
{
Bounds bounds = collider.bounds;
Vector3 point = new Vector3(
UnityEngine.Random.Range(bounds.min.x, bounds.max.x),
UnityEngine.Random.Range(bounds.min.y, bounds.max.y),
UnityEngine.Random.Range(bounds.min.z, bounds.max.z)
);
if (point != collider.ClosestPoint(point))
point = RandomPointInBounds(collider);
return point;
}
But this gave me so much random result. I want to spread the objects evenly.
I can check if any collider overlaps if it is reposition but this will cause many many many iterations even maybe infinity loop.
Any ideas how to do?
Answer by Robotinker · Aug 26, 2021 at 06:27 PM
Depends on how you want the object's filled pattern to look. If you just want a grid, here's how I'd approach it:
Calculate the volume of your mesh.
Divide that volume by the number of dots you're using to get the dot density you need.
Create an array of points within the collider's bounds that use the spacing you calculated in the previous step.
For each point, see if it's inside the collider mesh. If so, add it to some Destination list.
Iterate through your Destination and dot list in parallel and tell dots[i] to go to destinations[i]. The lists probably won't be exactly the same length, so if you have extra destinations ignore them. If you have more dots than destinations, you may want to just assign the destination of every remaining dot to one of the valid destinations so that they "hide" behind one of them. This also assumes that you want this to be animated and you have some sort of component on the dots that you can tell the destination to that will manage its movement toward that destination.
Your answer
