Unity 旋轉發散生成物體
阿新 • • 發佈:2018-12-10
以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; } } }