注释
简单的随机生成UI且不发生重叠,可以修改算法进行更深入的探索
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CellInfo
{
/// <summary>
/// 物体位置
/// </summary>
public Vector2 pos;
/// <summary>
/// 物体宽
/// </summary>
public float width;
/// <summary>
/// 物体高
/// </summary>
public float height;
}
/// <summary>
/// 屏幕随机生成文字并不叠加
/// </summary>
public class TextTest : MonoBehaviour
{
/// <summary>
/// 外面的父级
/// </summary>
public RectTransform parent;
/// <summary>
/// 想要显示的子物体集合
/// </summary>
[Header("想要显示的子物体集合")]
public List<GameObject> cells = new List<GameObject>();
/// <summary>
/// 已经存在的子物体信息
/// </summary>
private List<CellInfo> hadCells = new List<CellInfo>();
/// <summary>
/// 最大尝试的次数
/// </summary>
[Header("最大尝试的次数")]
public int maxIndex;
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
StartCoroutine(CreateGameObject());
}
}
/// <summary>
/// 生成图片
/// </summary>
/// <returns></returns>
public IEnumerator CreateGameObject()
{
int i = 0;
while (i < cells.Count)
{
float ItmeWidth = cells[i].GetComponent<RectTransform>().rect.width / 2;
float ItmeHeigh = cells[i].GetComponent<RectTransform>().rect.height / 2;
Vector2 cellPos = new Vector2(Random.Range(ItmeWidth, parent.rect.width - ItmeWidth),
Random.Range(ItmeHeigh, parent.rect.height - ItmeHeigh));
//尝试更新新坐标的次数
int index = 0;
while (index < maxIndex)
{
if (i == 0 || (i != 0 && TwoPointDistance2D2(cellPos, ItmeWidth, ItmeHeigh)))
{
CellInfo cellinfo = new CellInfo();
cellinfo.pos = cellPos;
cellinfo.width = ItmeWidth;
cellinfo.height = ItmeHeigh;
hadCells.Add(cellinfo);
GameObject obj = Instantiate<GameObject>(cells[i], parent);
obj.GetComponent<RectTransform>().position = cellPos;
break;
}
index++;
}
i++;
yield return null;
}
}
/// <summary>
/// 进行距离比较
/// </summary>
/// <param name="p1"></param>
/// <param name="p2"></param>
/// <returns></returns>
private bool TwoPointDistance2D2(Vector2 currentPos, float w, float h)
{
float x1 = currentPos.x - w;
float x2 = currentPos.x + w;
float y1 = currentPos.y - h;
float y2 = currentPos.y + h;
for (int i = 0; i < hadCells.Count; i++)
{
float x11 = hadCells[i].pos.x - hadCells[i].width;
float x22 = hadCells[i].pos.x + hadCells[i].width;
float y11 = hadCells[i].pos.y - hadCells[i].height;
float y22 = hadCells[i].pos.y + hadCells[i].height;
if ((x2 < x11 || x1 > x22) && (y1 > y22 || y2 < y11))
{
continue;
}
else
{
return false;
}
}
return true;
}
}