游戏地图的制作:

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(-mapWidth/2,-mapHeight/2+y*gridHeight);Gizmos.DrawLine(startPos,endPos);}//画列for (int x = 0; x < xColumn; x++){Vector3 startPos = new Vector3(-mapWidth / 2 + gridWidth * x, mapHeight / 2);Vector3 endPos = new Vector3(-mapWidth / 2 + x * gridWidth, -mapHeight / 2);Gizmos.DrawLine(startPos, endPos);}}}}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class GridPoint : MonoBehaviour {//属性private SpriteRenderer spriteRenderer;public GridState gridState;public GridIndex gridIndex;//资源private Sprite gridSprite;//格子图片资源private Sprite monsterPathSprite;//怪物路点图片资源public GameObject[] itemPrefabs;//道具数组public GameObject currentItem;//当前格子持有道具//格子状态public struct GridState{public bool canBuild;public bool hasItem;public bool isMonsterPoint;public int itemID;}//格子索引public struct GridIndex{public int xIndex;public int yIndex;}private void Awake(){spriteRenderer = GetComponent<SpriteRenderer>();gridSprite = Resources.Load<Sprite>("Pictures/NormalMordel/Game/Grid");monsterPathSprite = Resources.Load<Sprite>("Pictures/NormalMordel/Game/1/Monster/6-1");itemPrefabs = new GameObject[10];string prefabsPath = "Prefabs/Game/" + MapMaker.Instance.bigLevelID.ToString() + "/Item/";for (int i = 0; i < itemPrefabs.Length; i++){itemPrefabs[i] = Resources.Load<GameObject>(prefabsPath + i);if (!itemPrefabs[i]){Debug.Log("加载失败,失败路径:" + prefabsPath + i);}}InitGrid();}public void InitGrid(){gridState.canBuild = true;gridState.hasItem = false;gridState.isMonsterPoint = false;gridState.itemID = -1;spriteRenderer.sprite = gridSprite;Destroy(currentItem);}private void OnMouseDown(){//怪物路点if (Input.GetKey(KeyCode.P)){gridState.canBuild = false;spriteRenderer.enabled = true;gridState.isMonsterPoint = !gridState.isMonsterPoint;if (gridState.isMonsterPoint){MapMaker.Instance.monsterPath.Add(gridIndex);spriteRenderer.sprite = monsterPathSprite;}else{MapMaker.Instance.monsterPath.Remove(gridIndex);spriteRenderer.sprite = gridSprite;gridState.canBuild = true;}}//道具else if (Input.GetKey(KeyCode.I)){gridState.itemID++;//当前格子从持有道具状态转化为没有道具if (gridState.itemID == itemPrefabs.Length){gridState.hasItem = false;gridState.itemID = -1;Destroy(currentItem);return;}//本身没有道具if (currentItem == null){CreateItem();}//本身就有道具else{Destroy(currentItem);CreateItem();}gridState.hasItem = true;}else if (!gridState.isMonsterPoint){gridState.isMonsterPoint = false;gridState.canBuild = !gridState.canBuild;if (gridState.canBuild){spriteRenderer.enabled = true;}else{spriteRenderer.enabled = false;}}}//生成道具public void CreateItem(){Vector3 createPos = transform.position;//游戏道具大小不同,只占一个格子就不用判断语句了!if (gridState.itemID <= 2){createPos += new Vector3(MapMaker.Instance.gridWidth, -MapMaker.Instance.gridHeight) / 2;}else if (gridState.itemID <= 4){createPos += new Vector3(MapMaker.Instance.gridWidth, 0) / 2;}GameObject itemGo = Instantiate(itemPrefabs[gridState.itemID], createPos, Quaternion.identity);currentItem = itemGo;}}

运行后界面:(可按不同的键对地图进行编辑)

地图信息的存储:

在GridPoint中加入更新格子状态信息的方法

    //更新格子状态public void UpdateGridState(){if (gridState.canBuild){spriteRenderer.sprite = gridSprite;spriteRenderer.enabled = true;if (gridState.hasItem){CreateItem();}}else{if (gridState.isMonsterPoint){spriteRenderer.sprite = monsterPathSprite;}else{spriteRenderer.enabled = false;}}}

在MapMaker中声明有关地图信息的存储的方法:

    /// <summary>/// 清除怪物路点/// </summary>public void ClearMonsterPath(){monsterPath.Clear();}/// <summary>/// 恢复地图编辑默认状态/// </summary>public void RecoverMapDefaultState(){ClearMonsterPath();for (int x = 0; x < xColumn; x++){for (int y = 0; y < yRow; y++){gridPoints[x, y].InitGrid();}}}/// <summary>///  初始化地图/// </summary>public void InitMap(){bigLevelID = 0;levelID = 0;RecoverMapDefaultState();roundInfoList.Clear();bgSR = null;roadSR = null;}//生成LevelInfo对象用来保存文件public LevelInfo CreateLevelInfoGo(){LevelInfo levelInfo = new LevelInfo(){bigLevelID = this.bigLevelID,levelID = this.levelID};levelInfo.gridStateList = new List<GridPoint.GridState>();for (int x = 0; x < xColumn; x++){for (int y = 0; y < yRow; y++){levelInfo.gridStateList.Add(gridPoints[x, y].gridState);}}levelInfo.monsterPathList = new List<GridPoint.GridIndex>();for (int i = 0; i < monsterPath.Count; i++){levelInfo.monsterPathList.Add(monsterPath[i]);}levelInfo.roundInfoList = new List<Round.RoundInfo>();for (int i = 0; i < roundInfoList.Count; i++){levelInfo.roundInfoList.Add(roundInfoList[i]);}return levelInfo;}//保存当前关卡的数据文件public void SaveLevelFileByJson(){LevelInfo levelInfo = CreateLevelInfoGo();string filePath = Application.streamingAssetsPath + "/Json/Level/" + "Level" + bigLevelID.ToString() + "_" + levelID.ToString() + ".json";string saveJsonStr = JsonMapper.ToJson(levelInfo);StreamWriter sw = new StreamWriter(filePath);sw.Write(saveJsonStr);sw.Close();}public LevelInfo LoadLevelInfoFile(string fileName){LevelInfo levelInfo = new LevelInfo();string filePath = Application.streamingAssetsPath + "/Json/Level/" + fileName;if (File.Exists(filePath)){StreamReader sr = new StreamReader(filePath);string jsonStr = sr.ReadToEnd();sr.Close();levelInfo = JsonMapper.ToObject<LevelInfo>(jsonStr);return levelInfo;}Debug.Log("文件加载失败,加载路径是" + filePath);return null;}public void LoadLevelFile(LevelInfo levelInfo){bigLevelID = levelInfo.bigLevelID;levelID = levelInfo.levelID;for (int x = 0; x < xColumn; x++){for (int y = 0; y < yRow; y++){gridPoints[x, y].gridState = levelInfo.gridStateList[y + x * yRow];//更新格子的状态gridPoints[x, y].UpdateGridState();}}monsterPath.Clear();for (int i = 0; i < levelInfo.monsterPathList.Count; i++){monsterPath.Add(levelInfo.monsterPathList[i]);}roundInfoList = new List<Round.RoundInfo>();for (int i = 0; i < levelInfo.roundInfoList.Count; i++){roundInfoList.Add(levelInfo.roundInfoList[i]);}}

制作地图信息的工具类

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;//定义自定义编辑器类可以编辑的对象类型。
[CustomEditor(typeof(MapMaker))]
public class MapMakerTool : Editor
{private MapMaker mapMaker;//关卡文件列表private List<FileInfo> fileList = new List<FileInfo>();//文件名数组private string[] fileNameList;//当前编辑的关卡索引private int selectIndex = -1;public override void OnInspectorGUI(){base.OnInspectorGUI();if (Application.isPlaying){mapMaker = MapMaker.Instance;EditorGUILayout.BeginHorizontal();//获取操作的文件名fileNameList = GetNames(fileList);int currentIndex = EditorGUILayout.Popup(selectIndex, fileNameList);//获取操作的文件名if (currentIndex != selectIndex){selectIndex = currentIndex;//实例化地图mapMaker.InitMap();//加载当前选择的level文件mapMaker.LoadLevelFile(mapMaker.LoadLevelInfoFile(fileNameList[selectIndex]));}if (GUILayout.Button("读取关卡列表")){LoadLevelFiles();}EditorGUILayout.EndHorizontal();EditorGUILayout.BeginHorizontal();if (GUILayout.Button("回复地图编辑器默认状态")){mapMaker.RecoverMapDefaultState();}if (GUILayout.Button("清除怪物路点")){mapMaker.ClearMonsterPath();}EditorGUILayout.EndHorizontal();if (GUILayout.Button("保存当前关卡数据文件")){mapMaker.SaveLevelFileByJson();}}}//加载关卡数据private void LoadLevelFiles(){ClearList();fileList = GetLevelFiles();}//清除文件列表private void ClearList(){fileList.Clear();selectIndex = -1;}//具体读取关卡列表private List<FileInfo> GetLevelFiles(){string[] files = Directory.GetFiles(Application.streamingAssetsPath + "/Json/Level/", "*.json");List<FileInfo> list = new List<FileInfo>();for (int i = 0; i < files.Length; i++){FileInfo file = new FileInfo(files[i]);list.Add(file);}return list;}//获取关卡文件的文字public string[] GetNames(List<FileInfo> files){List<string> names = new List<string>();foreach (FileInfo file in files){//存储关卡名字names.Add(file.Name);}return names.ToArray();}}

运行后效果:

可对地图进行编辑:

点击保存当前关卡数据文件 按钮

再按恢复地图编辑器默认状态 按钮 则 清空界面为初始状态

最后按读取关卡列表,弹框中会出现你所有的关卡名称信息,选择关卡即可加载关卡。

此时,JSON文件也会存储在你的文件夹中   (可在BeJson网站中校验JSON文件是否正确)

地图编辑完成

unity游戏开发(三):游戏地图的制作及地图信息的存储(LitJson)相关推荐

  1. ​Unity 游戏开发技巧集锦之制作一个望远镜与查看器摄像机

    ​Unity 游戏开发技巧集锦之制作一个望远镜与查看器摄像机 Unity中制作一个望远镜 本节制作的望远镜,在鼠标左键按下时,看到的视图会变大:当不再按下的时候,会慢慢缩小成原来的视图.游戏中时常出现 ...

  2. Unity游戏开发——新发教你做游戏(三):3种资源加载方式

    文章目录 一.前言 二.Unity的目录结构规范 1.Resources(不是很推荐把资源放这个目录) 2.RawAssets(存放生资源) 3.GameRes(存放熟资源) 4.StreamingA ...

  3. unity 角度限制_喵的Unity游戏开发之路 推球:游戏中的物理

    前言很多童鞋没有系统的Unity3D游戏开发基础,也不知道从何开始学.为此我们精选了一套国外优秀的Unity3D游戏开发教程,翻译整理后放送给大家,教您从零开始一步一步掌握Unity3D游戏开发. 本 ...

  4. confluence 编辑器这次没有加载_喵的Unity游戏开发之路 - 多场景:场景加载

    如果丢失格式.图片或视频,请查看原文:喵的Unity游戏开发之路 - 多场景:场景加载 很多童鞋没有系统的Unity3D游戏开发基础,也不知道从何开始学.为此我们精选了一套国外优秀的Unity3D游戏 ...

  5. 喵的Unity游戏开发之路 - 推球:游戏中的物理

    很多童鞋没有系统的Unity3D游戏开发基础,也不知道从何开始学.为此我们精选了一套国外优秀的Unity3D游戏开发教程,翻译整理后放送给大家,教您从零开始一步一步掌握Unity3D游戏开发. 本文不 ...

  6. 从零开始的种田生活-Unity游戏开发

    从零开始的种田生活-Unity游戏开发 CSV中的静态数据读取 Json中的动态数据读取 ScriptableObject的使用 大家好,这里是暴躁老哥酒九.最近了我们的童年记忆<摩尔庄园> ...

  7. 喵的Unity游戏开发之路 - 游泳

    原文: https://mp.weixin.qq.com/s/-ERFNB1GRZ6UAkHOhP9UQw 很多童鞋没有系统的Unity3D游戏开发基础,也不知道从何开始学.为此我们精选了一套国外优秀 ...

  8. Unity游戏开发——新发教你做游戏(一):打开游戏开发新世界的大门

    文章目录 一.前言 二.制作思路 三.提出问题 四.具体实现 一.前言 嗨,大家好,我是新发,如下,我做了个简单的Demo,接下来我会详细介绍如何一步步制作,Demo工程我已上传到GitHub,感兴趣 ...

  9. 1.15 从0开始学习Unity游戏开发--游戏UI

    上一章中,我们剩下最后一个任务,需要支持鼠标控制准心来进行设计,那么准心本质上就是一个始终呈现在屏幕上的一个图片,你当然可以用一个3D物体来制作,之前讲解渲染概念的时候也提到过,我们的屏幕就是相机的近 ...

最新文章

  1. 【赫夫曼树详解】赫夫曼树简介及java代码实现-数据结构07
  2. 小甲鱼python视频解读_小甲鱼python视频弟十二讲(关于字符串的方法及注释下)...
  3. ArrayList,LinkedList,Vector的异同点
  4. 使用Hybris的customer conpon进行促销活动(promotion)
  5. java finereport_java报表工具FineReport常见的数据集报错错误代码和解释
  6. Unity3D学习笔记之九为场景添加细节(二)
  7. 2 未匹配到任何借口_拼多多【关键词精确匹配溢价】给你想要的精准流量,让你订单暴增的秘诀...
  8. 【JDBC】Eclipse连接Mysql
  9. 在winform上内嵌入其它的程序
  10. 在ACCESS中使用Group By语句
  11. 详解如何在ubuntu上安装node.js
  12. Magento重建所有索引方法
  13. 关于router-link包含dom元素会出现Warnings while compiling.警告的问题!
  14. 开课吧python小课学了有用吗-和年薪百万的CFO大佬聊天后,我慌了!
  15. anaconda-ks.cfg详解
  16. f分布表完整图a=0.01_第7章 分布分析
  17. 已安装flash插件,chrome仍提示未安装的解决方法
  18. BatchShell服务器批量管理工具功能介绍
  19. 简约资源教程分享网模板,emlog模板
  20. python录音功能,python实现录音功能可随时停止录音代码

热门文章

  1. PS初学——基本工具(一)
  2. WebGL—实现使用FBO离屏渲染(亦同拷贝纹理)off-screen rendering的两种方式
  3. 创建一套电商店铺使用的数据库
  4. 横竖屏和界面不同分辨率适配
  5. lol显示服务器正忙请稍后再试,LOL客户端报错崩溃怎么办_无法进入队列及服务器正忙提示解决方法一览_3DM网游...
  6. 2016年央视315晚会互联网成重灾区!
  7. BarTender 2016如何导出模板为pdf文件?
  8. Compare to 方法详解
  9. 历届试题 格子刷油漆
  10. 华夏银行软件测试,华夏银行测试信息管理系统项目