游戏地图的制作:
ps:资源的获取自己定义
格子图片:
在游戏物体格子上挂载脚本:GridPoint,创建一个空物体,挂载MapMaker脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MapMaker : MonoBehaviour
{
//是否画线
public bool drawLine;
//格子预制体
public GameObject gridGO;
//当前关卡索引
public int bigLevelID;
public int levelID;
//地图
public float mapWidth;
public float mapHeight;
//格子
public float gridWidth;
public float gridHeight;
//全部的格子对象
public GridPoint[,] gridPoints;
//行列
public int xColumn = 12;
public int yRow = 8;
private SpriteRenderer bgSR;
private SpriteRenderer roadSR;
/// <summary>
/// 怪物路径点
/// </summary>
public List<GridPoint.GridIndex> monsterPath;
/// <summary>
/// 怪物路径点的具体位置
/// </summary>
public List<Vector3> monsterPathPos;
public static MapMaker _instance;
public static MapMaker Instance
{
get { return _instance; }
}
private void Awake()
{
_instance = this;
InitMapMaker();
}
//初始化地图
public void InitMapMaker()
{
CalculateSize();
gridPoints = new GridPoint[xColumn, yRow];
monsterPath = new List<GridPoint.GridIndex>();
for (int x = 0; x < xColumn; x++)
{
for (int y = 0; y < yRow; y++)
{
GameObject itemGo = Instantiate(gridGO,transform.position,transform.rotation);
itemGo.transform.position = CorretPostion(x*gridWidth,y*gridHeight);
itemGo.transform.SetParent(transform);
gridPoints[x, y] = itemGo.GetComponent<GridPoint>();
gridPoints[x, y].gridIndex.xIndex = x;
gridPoints[x, y].gridIndex.yIndex = y;
}
}
bgSR = transform.Find("BG").GetComponent<SpriteRenderer>();
roadSR = transform.Find("Road").GetComponent<SpriteRenderer>();
}
//纠正位置
public Vector3 CorretPostion(float x, float y)
{
return new Vector3(x - mapWidth / 2 + gridWidth / 2, y - mapHeight / 2 + gridHeight / 2);
}
//计算地图格子宽高
private void CalculateSize()
{
Vector3 leftDown = new Vector3(0, 0);
Vector3 rightUp = new Vector3(1,1);
Vector3 posOne = Camera.main.ViewportToWorldPoint(leftDown);
Vector3 posTwo = Camera.main.ViewportToWorldPoint(rightUp);
mapWidth = posTwo.x - posOne.x;
mapHeight = posTwo.y - posOne.y;
gridWidth = mapWidth / xColumn;
gridHeight = mapHeight / yRow;
}
//画格子用于辅助设计
private void OnDrawGizmos()
{
if (drawLine)
{
CalculateSize();
Gizmos.color = Color.red;
//画行
for (int y = 0; y <= yRow; y++)
{
Vector3 endPos = new Vector3(mapWidth / 2, -mapHeight / 2 + y * gridHeight);
Vector3 startPos = new Vector3(-mapW