Net_Ease_Dome/Assets/Scripts/Grids/GridMange.cs

100 lines
2.7 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class GridMange : MonoBehaviour
{
public Transform PlayerTrans; //Player
public List<GridElements> Grids = new List<GridElements>(); //所有格子
public byte[] CurrentIndex = new byte[2];
public Rect CurrentRect = new Rect();
Coroutine selfCoroutine = null;
// Start is called before the first frame update
void Start()
{
Grids = GetComponentsInChildren<GridElements>().ToList();
selfCoroutine = StartCoroutine(UpdateSelfPosInfo());
}
/// <summary>
/// 获取自身格子信息
/// </summary>
void GetSelfGridInfo()
{
if (PlayerTrans == null) return;
Vector2 currentPos = new Vector2(PlayerTrans.position.x,PlayerTrans.position.z);
for (int i = 0; i < Grids.Count; i++)
{
if (Grids[i].MyRect.Contains(currentPos))
{
CurrentRect = Grids[i].MyRect;
CurrentIndex = new byte[] { Grids[i].x_Pos, Grids[i].z_Pos };
break;
}
}
}
IEnumerator UpdateSelfPosInfo()
{
while (true)
{
yield return new WaitForSeconds(1);
GetSelfGridInfo();
}
}
/// <summary>
/// 获取对应格子的生成点
/// </summary>
/// <param name="coordinate"></param>
/// <returns></returns>
public Vector3 GetGridInitPos(byte[] coordinate)
{
GridElements elements = Grids.Find(x => x.x_Pos.Equals(coordinate[0]) && x.z_Pos.Equals(coordinate[1]));
if (elements != null)
{
return elements.InitPos.position;
}
return Grids[0].InitPos.position;
}
private void Reset()
{
string sp = "";
for (int i = 0; i < transform.childCount; i++)
{
sp = string.Format("{0}_{1}", sp, transform.GetChild(i).name);
}
Debug.Log(sp);
return;
GridElements[] childs = GetComponentsInChildren<GridElements>();
for (int i = 0; i < childs.Length; i++)
{
GridElements element = childs[i];
int e_x = int.Parse(element.name[0].ToString());
int e_z = int.Parse(element.name[1].ToString());
for (int j = 0; j < childs.Length; j++)
{
GridElements temp = childs[j];
int chax = Mathf.Abs(int.Parse(temp.name[0].ToString()) - e_x );
int chaz = Mathf.Abs(int.Parse(temp.name[1].ToString()) - e_z );
if (chax <= 1 && chaz <= 1)
{
if (element != temp)
element.NearGrids.Add(temp);
}
}
}
}
}