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));
}
}
随机生成房间(一)
于 2022-01-23 15:37:42 首次发布