网格系统
1. 建立网格
网格分析:网格宽、高、间隔、网格里面的内容、网格的起点
using TMPro;
using UnityEngine;
/// <summary>
/// 网格类
/// </summary>
public class Grid<TGridObject>
{
private Vector3 originPos;
private int width;
private int height;
private float cellSize;
private TGridObject[,] gridArray;
private TextMeshPro[,] textMeshProArray;
/// <summary>
/// 顶点数
/// </summary>
private Vector3[] vertices;
public Grid(int width, int height, float cellSize, Vector3 originPos) {
this.width = width;
this.height = height;
this.cellSize = cellSize;
this.originPos = originPos;
this.gridArray = new TGridObject[width, height];
textMeshProArray = new TextMeshPro[width, height];
vertices = new Vector3[(width+1)*(height+1)];
//for (int x = 0; x < width; x++)
//{
// for(int y = 0; y < height; y++)
// {
// textMeshProArray[x,y] = DYCreateUtils.CreateWroldTextPro(gridArray[x,y].ToString(), "WorldGrid", null, GetWorldPos(x+0.5f,y+0.5f));
// Debug.DrawLine(GetWorldPos(x, y), GetWorldPos(x+1, y), Color.white, 100f);
// Debug.DrawLine(GetWorldPos(x, y), GetWorldPos(x, y+1), Color.white, 100f);
// }
//}
//Debug.DrawLine(GetWorldPos(width, 0), GetWorldPos(width, height), Color.white, 100f);
//Debug.DrawLine(GetWorldPos(0, height), GetWorldPos(width, height), Color.white, 100f);
}
public Vector3[] GetVertices()
{
return vertices;
}
public void SetVertices(int index, Vector3 worldPos)
{
if (index < 0 || index >= vertices.Length) return;
vertices[index] = worldPos;
}
private void SetValue(int x, int y, TGridObject value)
{
if(x < 0 || y < 0 && x>width || y >height)
{
return;
}
gridArray[x, y] = value;
textMeshProArray[x, y].text = value.ToString();
}
/// <summary>
/// 点击网格小方块内,修改对应方块的内容
/// </summary>
/// <param name="mouseWorldPos">对应的世界坐标</param>
/// <param name="value">修改的内容</param>
public void SetValue(Vector3 mouseWorldPos, TGridObject value)
{
int x = Mathf.FloorToInt((mouseWorldPos.x - originPos.x) / cellSize);
int y = Mathf.FloorToInt((mouseWorldPos.y - originPos.y) / cellSize);
SetValue(x, y, value);
}
/// <summary>
/// 根据数组位置修改对应的值
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="value"></param>
public void SetValueForXY(int x, int y, TGridObject value)
{
if (x < 0 || y < 0 && x > width || y > height)
{
return;
}
gridArray[x, y] = value;
textMeshProArray[x, y].text = value.ToString();
}
/// <summary>
/// 通过x,y获得对应grid的值
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
public TGridObject GetValueForXY(int x, int y)
{
if (x < 0 || y < 0 && x > width || y > height)
{
return default(TGridObject);
}
return gridArray[x, y];
}
public Vector3 GetWorldPos(float x, float y)
{
return new Vector3(x, y) * cellSize + originPos;
}
}
评论区