随机生成UI不重叠

注释

简单的随机生成UI且不发生重叠,可以修改算法进行更深入的探索

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CellInfo
{
    /// 
    /// 物体位置
    /// 
    public Vector2 pos;
    /// 
    /// 物体宽
    /// 
    public float width;
    /// 
    /// 物体高
    /// 
    public float height;
}


/// 
/// 屏幕随机生成文字并不叠加
/// 

public class TextTest : MonoBehaviour
{
    /// 
    /// 外面的父级
    /// 
    public RectTransform parent;
    /// 
    /// 想要显示的子物体集合
    /// 
    [Header("想要显示的子物体集合")]
    public List cells = new List();
    /// 
    /// 已经存在的子物体信息
    /// 
    private List hadCells = new List();
    /// 
    /// 最大尝试的次数
    /// 
    [Header("最大尝试的次数")]
    public int maxIndex;


    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            StartCoroutine(CreateGameObject());
        }
    }

    /// 
    /// 生成图片
    /// 
    /// 
    public IEnumerator CreateGameObject()
    {
        int i = 0;
        while (i < cells.Count)
        {
            float ItmeWidth = cells[i].GetComponent().rect.width / 2;
            float ItmeHeigh = cells[i].GetComponent().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(cells[i], parent);
                    obj.GetComponent().position = cellPos;
                    break;
                }
                index++;
            }
            i++;
            yield return null;
        }
    }

    /// 
    /// 进行距离比较
    /// 
    /// 
    /// 
    /// 
    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;
    }
}

你可能感兴趣的:(ui)