通过学习YouTube的教程,学了一个简单的网格系统,所以在这做了个总结。
效果如图
点击网格可以修改里面的数字
其实在游戏开发中,可以使用这个去划分地图区域,例如植物大战僵尸,就可以用这个去划分地方区域,通过点击地图网格,生成植物,不过在这我们修改数字。
代码如下
using UnityEngine;
public class Grid
{
public int width; //长度
public int helight; //高度
public int cellSize; //格子尺寸
public Vector3 startPos; //起点坐标
public int[,] arrayCell; //网格数组,存储网格内容
public TextMesh[,] arrayTextMesh; //存储网格textmesh,具体是用来表现
public Grid(int width, int helight, int cellSize, Vector3 startPos)
{
this.width = width;
this.helight = helight;
this.cellSize = cellSize;
this.startPos = startPos;
arrayCell = new int[width, helight];
arrayTextMesh = new TextMesh[width, helight];
for (int i = 0; i < arrayCell.GetLength(0); i++)
{
for (int j = 0; j < arrayCell.GetLength(1); j++)
{
arrayTextMesh[i ,j] = SetText(arrayCell[i, j].ToString(), GetWorldPos(i, j) + new Vector3(cellSize, cellSize)*0.5f, Color.white);
Debug.DrawLine(GetWorldPos(i, j), GetWorldPos(i, j + 1), Color.black, 100f);
Debug.DrawLine(GetWorldPos(i, j), GetWorldPos(i+1, j), Color.black, 100f);
}
}
Debug.DrawLine(GetWorldPos(0, helight), GetWorldPos(width, helight), Color.black, 100f);
Debug.DrawLine(GetWorldPos(width, 0), GetWorldPos(width, helight), Color.black, 100f);
}
//偏移坐标
public Vector3 GetWorldPos(int x, int y)
{
return new Vector3(x, y) * cellSize + startPos;
}
//设置网格中的值
public void SetValue(int x, int y, int value)
{
if (x >= 0 & y >= 0 & x < width & y < helight)
{
arrayCell[x, y] = value;
arrayTextMesh[x, y].text = value.ToString();
}
}
//将点击的坐标传入
public void SetValue(Vector3 pos, int value)
{
int x, y;
GetXY(pos, out x, out y);
SetValue(x, y, value);
}
//将点击的坐标转化为网格中位置
public void GetXY(Vector3 pos, out int x, out int y)
{
x = Mathf.FloorToInt(pos.x / cellSize);
y = Mathf.FloorToInt(pos.y / cellSize);
}
//点击的表现,这里是修改网格内容
public TextMesh SetText(string text, Vector3 pos, Color color)
{
GameObject objText = new GameObject("WorldText", typeof(TextMesh));
TextMesh textMesh = objText.GetComponent<TextMesh>();
textMesh.text = text;
textMesh.color = color;
textMesh.alignment = TextAlignment.Center;
textMesh.anchor = TextAnchor.MiddleLeft;
textMesh.characterSize = 0.28f;
objText.transform.position = pos;
return textMesh;
}
}
调用的脚本:
using UnityEngine;
public class GridTest : MonoBehaviour
{
public Grid grid;
void Start()
{
grid = new Grid(10, 6, 2, Vector3.zero);
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
grid.SetValue(GetPos(), 1);
}
}
public Vector3 GetPos()
{
Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
pos.z = 0;
return pos;
}
}
随便一提
运行中,这个要点击,否则是看不到网格的