private GameObject PartObj;//控制范围的游戏物体,用碰撞器限制范围【在属性面板赋值】
public List<GameObject> partsLst = new List<GameObject>();//存储需要随机生成位置的物体 【在属性面板赋值】
public List<GameObject> putpartLst = new List<GameObject>();//存储已经生成位置的物体 【不需要赋值】
//执行函数 (n 不需要填也行)
void putInsideBounds(int n)
{
Bounds partFrame = PartObj.GetComponent<BoxCollider2D>().bounds;
while (partsLst.Count > 0)
{
GameObject piece = partsLst[0];
Bounds partBounds = piece.GetComponent<SpriteRenderer>().bounds;
float _x = Random.Range(partFrame.min.x + partBounds.extents.x, partFrame.max.x - partBounds.extents.x);
float _y = Random.Range(partFrame.min.y + partBounds.extents.y, partFrame.max.y - partBounds.extents.y);
piece.transform.position = new Vector3(_x, _y, PartObj.transform.position.z - 2);
Vector3 center = partFrame.center;
center.z = partBounds.center.z;
partFrame.center = center;
if (isoverlapothers(piece))//如果有重叠部分,重新生成位置
return;
if (partsLst.Count > 0)//如果待生成列表还有元素
{
partsLst.Remove(piece);//将第一个元素移除待生成列表
putpartLst.Insert(0, piece);//加入已生成列表
putInsideBounds(0);//为下一个元素生成位置
if (0 == partsLst.Count)//如果待生成列表没有元素,跳出循环
break;
putpartLst.Remove(piece);
partsLst.Insert(0, piece);
}
}
}
bool isoverlapothers(GameObject cur)
{
foreach (GameObject obj in putpartLst)
{
if (obj == cur)
continue;
Bounds otherbounds = obj.GetComponent<SpriteRenderer>().bounds;
Bounds curbounds = cur.GetComponent<SpriteRenderer>().bounds;
if (otherbounds.Intersects(curbounds))//是否相交
return true;
}
return false;
}