Unity-2D隨機生成地圖及障礙物(簡易版)

最近在做的一個2D像素遊戲 拾荒者 需要隨機生成地圖
類似於生成這樣的隨機地圖
這是地圖效果圖。
以下是生成地圖及障礙物的代碼。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// PR_sc
/// </summary>
public class MapManager : MonoBehaviour {
	//利用腳本生成地圖。 10*10的像素地圖

	public GameObject[] OutWallArray;
	public GameObject[] FloorArray;
	public GameObject[] WallArray;

	public int rows = 10;  //定義地圖的行列。
	public int cols = 10;

	public int minCountWall = 2;
	public int maxCountWall = 8;

	private Transform mapHolder;
	private List<Vector2> positionList = new List<Vector2>();

	// Use this for initialization
	void Start () {
		InitMap();
	}
	
	// Update is called once per frame
	void Update () {
		
	}

	private void InitMap()
	{
		mapHolder = new GameObject("Map").transform;// 設置一個父類管理生成的地圖
		for(int x = 0; x < cols; x++)
		{
			for(int y= 0; y < rows; y++)
			{
				if(x==0 ||y==0 || x == cols - 1 || y == rows - 1)//地圖最外面一圈是圍牆
				{
					int index = Random.Range(0, OutWallArray.Length);
					GameObject go = GameObject.Instantiate(OutWallArray[index], new Vector3(x, y, 0), Quaternion.identity) as GameObject;
					go.transform.SetParent(mapHolder);
				}
				else// 其餘是地板
				{
					int index = Random.Range(0, FloorArray.Length);
					GameObject go = GameObject.Instantiate(FloorArray[index], new Vector3(x, y, 0), Quaternion.identity) as GameObject;
					go.transform.SetParent(mapHolder);
				}
			}
		}
		positionList.Clear();
		for (int x = 2; x < cols - 2; x++)
		{
			for(int y=2; y < rows - 2; y++)
			{
				positionList.Add(new Vector2(x, y));
			}
		}
		//創建障礙物 食物 敵人
		//創建障礙物
		int WallCount = Random.Range(minCountWall, maxCountWall + 1);//隨機生成障礙物個數的範圍
		for(int i = 0; i < WallCount; i++)
		{
			//隨機取得位置
			int positionIndex = Random.Range(0, positionList.Count);
			Vector2 pos = positionList[positionIndex];
			positionList.RemoveAt(positionIndex);
			//隨機取得障礙物
			int WallIndex = Random.Range(0, WallArray.Length);
			GameObject go = GameObject.Instantiate(WallArray[WallIndex], pos, Quaternion.identity) as GameObject;
			go.transform.SetParent(mapHolder);
		}
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章