以0,0点为起始点,顺时针旋转向外生成物体,效果如下:
以一个最原始的方法实现,将这个整体分成8个域,坐标分析如下:
根据这8个区域的不同特性,进行坐标的变化,然后通过协程递归生成物体。
以UI生成为例:
/************************************************************
FileName: Test.cs
Author:牛国贤 Version :1.0 Date: 2018-09-15
Description:末零
************************************************************/
using System.Collections;
using UnityEngine;
namespace LastZero
{
public class Test : MonoBehaviour
{
public GameObject canvas;
private int length = 1;
private float timeInterval = 1;
private int num = 0;
private int x = 0;
private int y = 0;
private void Start()
{
StartCoroutine(Creat(5, 0.3f));
}
/// <summary>
/// 创建正方形
/// </summary>
/// <param name="len">边长</param>
/// <param name="time">时间间隔</param>
/// <returns></returns>
IEnumerator Creat(int len, float time)
{
if (num >= len * len)
{
num = 0;
StopAllCoroutines();
yield return 0;
}
PrefabController.GetPrefab("Image", canvas).GetComponent<RectTransform>().localPosition = new Vector3(x, y, 0) * 15;
num++;
if (x == y)
{
if (x >= 0)
x++;
else
y++;
}
else if (x + y == 0)
{
if (x > 0)
x--;
else
x++;
}
else if (x > y)
{
if (Mathf.Abs(x) > Mathf.Abs(y))
y--;
else
x--;
}
else if (x < y)
{
if (Mathf.Abs(x) > Mathf.Abs(y))
y++;
else
x++;
}
yield return new WaitForSeconds(time);
StartCoroutine(Creat(len, time));
}
}
}
预制体的获取:
/************************************************************
FileName: PrefabController.cs
Author:末零 Version :1.0 Date: 2018-4-18
Description:获取预制体
************************************************************/
using System.Collections;
using UnityEngine;
namespace LastZero
{
public class PrefabController : MonoBehaviour
{
/// <summary>
/// 获取预制体,并实例化
/// </summary>
/// <param name="name">预制体名字</param>
/// <returns>实例化出来的物体</returns>
public static GameObject GetPrefab(string name)
{
GameObject prefab = Resources.Load("Prefab/" + name) as GameObject;
GameObject obj = Instantiate(prefab);
obj.name = name;
obj.transform.localPosition = prefab.transform.localPosition;
obj.transform.localEulerAngles = prefab.transform.localEulerAngles;
return obj;
}
/// <summary>
/// 获取预制体,并实例化
/// </summary>
/// <param name="name">预制体名字</param>
/// <param name="parent">父物体</param>
/// <returns>实例化出来的物体</returns>
public static GameObject GetPrefab(string name, GameObject parent)
{
GameObject prefab = Resources.Load("Prefab/" + name) as GameObject;
GameObject obj = Instantiate(prefab);
obj.name = name;
obj.transform.parent = parent.transform;
obj.transform.localPosition = prefab.transform.localPosition;
obj.transform.localEulerAngles = prefab.transform.localEulerAngles;
return obj;
}
}
}