Hello all. I’m trying to spawn game objects around a tilemap by checking if the object will not collide with anything before placing it. I essentially have a Decor object that contains the Required Size of the Object prefab it holds. For some reason though, Physics2D.OverlapBox() does not return a hit even if the box overlaps the walls, which have a TilemapCollider2D with a CompositeCollider2D. I’ve been searching for hours to find a solution, but nothing so far. I have the composite colllider’s Geometry Type set to Polygons, since the Outlines mode only creates EdgeColliders that are infinitely thin. I even tried Outline mode and setting the EdgeRadius to something ridiculous like 20 and still nothing. Any help is appreciated.
Decor.cs
public class Decor : ScriptableObject
{
public Vector2Int RequiredSpace;
[Range(0f, 1f)]
public float Chance;
public GameObject ObjectPrefab;
public bool CanPlace(Vector3Int pos)
{
var temp = new Vector2Int(pos.x, pos.y);
return CanPlace(temp);
}
public bool CanPlace(Vector2Int pos)
{
var newPos = pos - (Vector2.one / 2);
var hit = Physics2D.OverlapBox(newPos, RequiredSpace, 0);
Color color = (hit != null) ? Color.white : Color.green;
Vector3 temp = new Vector3((float)newPos.x, (float)newPos.y, 0f);
Debug.DrawLine(temp, temp + Vector3.up * RequiredSpace.x, color);
Debug.DrawLine(temp, temp + Vector3.right * RequiredSpace.x, color);
Debug.DrawLine(temp + Vector3.right * RequiredSpace.x, temp + (Vector3.up + Vector3.right) * RequiredSpace.x, color);
Debug.DrawLine(temp + Vector3.up * RequiredSpace.x, temp + (Vector3.up + Vector3.right) * RequiredSpace.x, color);
Debug.Break();
return hit == null;
}
}
And the following is the code I’m using to place the objects:
foreach (var pos in floors.cellBounds.allPositionsWithin)
{
if (floors.HasTile(pos))
{
float roll = Random.Range(0, 1f);
if (roll <= decorDensity)
{
foreach (var possibleDecor in obstructiveDecorations)
{
roll = Random.Range(0f, 1f);
if (roll <= possibleDecor.Chance && possibleDecor.CanPlace(pos))
{
Instantiate(possibleDecor.ObjectPrefab, pos, Quaternion.identity);
break;
}
}
}
}
}
When Testing for the writing of this post, I actually can’t tell what’s going on because it seems like it does sometimes return hits and sometimes it doesn’t. See the second image what I mean.
Firstly here is my Tilemap setup:
And here is a run. Successful placements are in green, failed ones are in white.