随机生成房间(一)

sing System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class RoomGenerator : MonoBehaviour
{
	public enum Direction { up, down, left, right };//用于控制房间生成方向的枚举类型
	public Direction direction;

	[Header("房间信息")]
	public GameObject roomPrefab;//房间预制体
	public int roomNumber;//房间数量
	public Color startColor, endColor;//起始房间颜色
	public GameObject endRoom;

	[Header("位置控制")]
	public Transform genetorPoint;//生成位置
	public float xOffest;//水平偏移量
	public float yOffest;//竖直偏移量
	public LayerMask roomLayer;

	public List<GameObject> rooms = new List<GameObject>();//存储房间的列表

	private void Start()
	{
		for (int i = 0; i < roomNumber; i++)//摁两下Tab自动生成
		{
			rooms.Add(Instantiate(roomPrefab, genetorPoint.position, Quaternion.identity));
			ChangePointPosition();
		}
		foreach (var room in rooms)
		{
			endRoom = rooms[0];
			if (room.transform.position.sqrMagnitude > endRoom.transform.position.sqrMagnitude)
			{
				endRoom = room;
			}
			//sqrMagnitude用于比较两个Vector3的大小(相比magnitude精度有损失)
		}

		endRoom.GetComponent<SpriteRenderer>().color = endColor;
	}

	private void Update()
	{
		if (Input.anyKeyDown)//按下任意键重新生成
		{
			SceneManager.LoadScene(SceneManager.GetActiveScene().name);
		}
	}

	public void ChangePointPosition()
	{
		do
		{
			direction = (Direction)Random.Range(0, 4);//随机赋予变换方向变量direction上下左右中的某个数值
			switch (direction)//通过switch完成房间生成点的位置变换
			{
				case Direction.up:
					genetorPoint.position += new Vector3(0, yOffest, 0);
					break;
				case Direction.down:
					genetorPoint.position += new Vector3(0, -yOffest, 0);
					break;
				case Direction.left:
					genetorPoint.position += new Vector3(-xOffest, 0, 0);
					break;
				case Direction.right:
					genetorPoint.position += new Vector3(xOffest, 0, 0);
					break;
			}
		} while (Physics2D.OverlapCircle(genetorPoint.position, 0.2f, roomLayer));
	
	}
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值