001-unity2D游戏随机生成地图
生活随笔
收集整理的這篇文章主要介紹了
001-unity2D游戏随机生成地图
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
unity2D游戲隨機生成地圖
教程與素材地址出處
地圖控制腳本.cs(所有變量使用用中文便于理解,實際開發(fā)中請勿這樣使用)
using System.Collections; using System.Collections.Generic; using UnityEngine;public class 地圖腳本 : MonoBehaviour {public GameObject[] 圍墻;public GameObject[] 地板;public GameObject[] 障礙物;public GameObject[] 食物;public GameObject[] 敵人;public GameObject 出口;public GameObject 主角;private int 行 = 10;private int 列 = 10;private Transform 地圖管理;private List<Vector2> 地圖位置列表 = new List<Vector2>();private 游戲流程腳本 游戲流程;void Awake(){游戲流程 = this.GetComponent<游戲流程腳本>();地圖初始化();}// Update is called once per framevoid Update(){}private void 地圖初始化(){地圖管理 = new GameObject("地圖").transform;for (int x = 0; x < 行; x++){for (int y = 0; y < 列; y++){if (x == 0 || y == 0 || x == 行 - 1 || y == 列 - 1){GameObject.Instantiate( 隨機游戲物品(圍墻), new Vector3(x, y, 0), Quaternion.identity).transform.SetParent(地圖管理);//游戲?qū)ο?實例化(調(diào)用方法隨機游戲物品(圍墻),實例化到指定坐標(biāo),實力化旋轉(zhuǎn).不旋轉(zhuǎn)).形態(tài).設(shè)置父對象(地圖管理)}else{GameObject.Instantiate(隨機游戲物品(地板), new Vector3(x, y, 0), Quaternion.identity).transform.SetParent(地圖管理); }}}//地圖位置列表創(chuàng)建地圖位置列表.Clear();for (int x = 2; x < 行 - 2; x++){for (int y = 2; y < 列 - 2; y++){地圖位置列表.Add(new Vector2(x, y));}}//創(chuàng)建障礙物int 障礙物數(shù)量 = Random.Range(2, 9);物體實力化(障礙物數(shù)量, 障礙物);//創(chuàng)建出口GameObject.Instantiate(出口, new Vector2(8, 8), Quaternion.identity);// GameObject.Instantiate(主角, new Vector2(1, 1), Quaternion.identity);//創(chuàng)建食物int 食物數(shù)量 = Random.Range(2, 游戲流程.當(dāng)前關(guān)卡 /4 + 1);物體實力化(食物數(shù)量, 食物);//創(chuàng)建敵人int 敵人數(shù)量 = 游戲流程.當(dāng)前關(guān)卡 / 4;物體實力化(敵人數(shù)量, 敵人);}//游戲物體實力化方法private void 物體實力化(int 數(shù)量,GameObject[] 預(yù)制體數(shù)組) {for (int i = 0; i < 數(shù)量; i++){GameObject.Instantiate(隨機游戲物品(預(yù)制體數(shù)組), 隨機位置(), Quaternion.identity).transform.SetParent(地圖管理);}}//取隨機位置方法private Vector2 隨機位置(){int 隨機位置列表索引 = Random.Range(0, 地圖位置列表.Count);Vector2 隨機生成位置坐標(biāo) = 地圖位置列表[隨機位置列表索引];地圖位置列表.RemoveAt(隨機位置列表索引);return 隨機生成位置坐標(biāo);}//取隨機游戲物品方法private GameObject 隨機游戲物品(GameObject[] 預(yù)制體數(shù)組){int 游戲物品數(shù)組索引 = Random.Range(0, 預(yù)制體數(shù)組.Length);return 預(yù)制體數(shù)組[游戲物品數(shù)組索引];} }游戲流程腳本.cs
using System.Collections; using System.Collections.Generic; using UnityEngine;public class 游戲流程腳本 : MonoBehaviour {public int 當(dāng)前關(guān)卡 = 1;// Start is called before the first frame updatevoid Start(){}// Update is called once per framevoid Update(){} }?
總結(jié)
以上是生活随笔為你收集整理的001-unity2D游戏随机生成地图的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据挖掘的一般流程
- 下一篇: 【MySQL】MySQL分库分表详解