- Home /
Instantiate within boundaries of Mesh shape
Hi all, I want to spawn certain gameobjects, but only within the boundaries of certain meshes. Below is a picture of what a shape could look like. Tried to find it before asking, but couldn't find what I needed. I know how to spawn at the vertices, now just a way to fill the spaces between the verts. Excuse me for my mediocre English.
Answer by Buckslice · Dec 05, 2017 at 12:02 AM
Probably the simplest way would be to generate random points in the Collider2D.bounds of the polygon then use Collider2D.OverlapPoint to check if they are inside the actual polygon.
Answer by SilverHuber · Dec 05, 2017 at 11:35 AM
Thanks!! So it worked for the biggest part. The only problem is the offset in the bounds. I get different offsets depending on the scale of the spawner. Maybe the center is wrong?
Collider2D thisCollider = GetComponent <PolygonCollider2D> ();
Bounds bounds = thisCollider.bounds;
float rangeOfX = (bounds.size.x * 0.5f);
float rangeOfY = (bounds.size.y * 0.5f);
Vector3 newVec = transform.TransformPoint (new Vector3 (Random.Range (-rangeOfX, rangeOfX), Random.Range (-rangeOfY, rangeOfY), spawnedObject.transform.position.z));
spawnedObject.transform.position = newVec;
Below some pictures of the result: Without overlap check
With overlap check
Use bounds.$$anonymous$$ and bounds.max, something like this
Collider2D thisCollider = GetComponent <PolygonCollider2D> ();
Bounds bounds = thisCollider.bounds;
for(int i = 0; i < count; ++i){
float x = Random.Range(bounds.$$anonymous$$.x, bounds.max.x);
float y = Random.Range(bounds.$$anonymous$$.y, bounds.max.y);
if(col.OverlapPoint(new Vector2(x,y))){
Vector3 spawn = new Vector3(x,y,0);
GameObject spawnedObject = Instatiate(prefabObject,spawn,Quaternion.identity);
}else{
continue;
}
}
Perfect! That is exactly what I needed. One last question: is there a way to make sure every created instance is within the mesh?
if(col.OverlapPoint(new Vector2(x,y))){
Vector3 spawn = new Vector3(x,y,0);
GameObject spawnedObject = Instatiate(prefabObject,spawn,Quaternion.identity);
}else{
//generate new spawn until the spawn is overlapped.
}
Isn't that what we have accomplished? Everything should spawn inside the mesh, or do you mean like where the smaller objects can still spawn and hang off the edge of the main shape and how to prevent that? If so I would just downscale the main collider shape a little bit to offset it.
Your answer
Follow this Question
Related Questions
unity3d can't create instantiated reference in awake 1 Answer
Getting Bounding box from a collider with children 1 Answer
Bounds of dynamic mesh not updating 1 Answer
Instantiating prefabs within the MeshFilter volume of object 1 Answer
not working- GameObject.GetComponent(MeshFilter).mesh; 1 Answer