Room房间随机生成器

代码:

using 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("room info")]

    public GameObject roomPrefab;

    public int roomNumber;

    public Color startColor, endColor;

    private GameObject endRoom;


 

    [Header("position control")]

    public Transform generatorPoint;

    public float xOffset;

    public float yOffset;

    //repeat room check layer

    public LayerMask roomLayer;

    //room list

    public List<GameObject> rooms = new List<GameObject>();

    void Start()

    {

        for (int i = 0; i < roomNumber; i++)

        {

            rooms.Add(Instantiate(roomPrefab, generatorPoint.position, Quaternion.identity));

            //change position

            ChangePointPos();

        }

        rooms[0].GetComponent<SpriteRenderer>().color = startColor;

        //compare the longest distance as the end room

        endRoom = rooms[0];

        foreach (var room in rooms)

        {

            //the begin room is 0,0,0

            if (room.transform.position.sqrMagnitude > endRoom.transform.position.sqrMagnitude)

            {

                endRoom = room;

            }

        }

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

    }

    // Update is called once per frame

    void Update()

    {

        if (Input.anyKeyDown)

        {

            SceneManager.LoadScene(SceneManager.GetActiveScene().name);

        }

    }

    public void ChangePointPos()

    {

        //check repeat

        do

        {

            direction = (Direction)Random.Range(0, 4);

            switch (direction)

            {

                case Direction.up:

                    generatorPoint.position += new Vector3(0, yOffset, 0);

                    break;

                case Direction.down:

                    generatorPoint.position += new Vector3(0, -yOffset, 0);

                    break;

                case Direction.left:

                    generatorPoint.position += new Vector3(-xOffset, 0, 0);

                    break;

                case Direction.right:

                    generatorPoint.position += new Vector3(xOffset, 0, 0);

                    break;

            }

        } while (Physics2D.OverlapCircle(generatorPoint.position, 0.2f, roomLayer));

    }

}

按照数量随机生成不同的房间在各个位置,开始和结束颜色不同

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值