我创建了一些框来重新创建一个 2D 关卡,其中地牢是在程序生成中创建的。尽管如此,当我运行我的脚本时,它会创建正确的关卡,但它不会将 Spawnpoints 彼此对齐。
这会导致无限的关卡生成(因为生成点不接触),但它也确保角色无法从一种方式转到另一种方式。我确保每个级别都是 10 x 10 并且生成点距离房间中间 10 像素。我想确保生成点之间发生碰撞,但不幸的是,事实并非如此。
我创建了多个房间,每个房间都有自己的出口(生成点),具体取决于生成点的位置,它可以与另一个具有相同生成点的房间连接(左侧出口的房间与至少一个右出口)。
我把所有这些都放在一个 int 中,声明可用房间的数量。
房间生成器代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RoomSpawner : MonoBehaviour
{
public int openingDirection;
// 1 --> need bottom door
// 2 --> need top door
// 3 --> need left door
// 4 --> need right door
private RoomTemplates templates;
private int rand;
private bool spawned = false;
void Start(){
templates = GameObject.FindGameObjectWithTag("Rooms").GetComponent<RoomTemplates>();
Invoke("Spawn", 0.5f);
}
void Spawn(){
if(spawned == false){
if(openingDirection == 1){
// Need to spawn a room with a BOTTOM door.
rand = Random.Range(0, templates.bottomRooms.Length);
Instantiate(templates.bottomRooms[rand], transform.position, templates.bottomRooms[rand].transform.rotation);
} else if(openingDirection == 2){
// Need to spawn a room with a TOP door.
rand = Random.Range(0, templates.topRooms.Length);
Instantiate(templates.topRooms[rand], transform.position, templates.topRooms[rand].transform.rotation);
} else if(openingDirection == 3){
// Need to spawn a room with a LEFT door.
rand = Random.Range(0, templates.leftRooms.Length);
Instantiate(templates.leftRooms[rand], transform.position, templates.leftRooms[rand].transform.rotation);
} else if(openingDirection == 4){
// Need to spawn a room with a RIGHT door.
rand = Random.Range(0, templates.rightRooms.Length);
Instantiate(templates.rightRooms[rand], transform.position, templates.rightRooms[rand].transform.rotation);
}
spawned = true;
}
void OnTriggerEnter2D(Collider2D other){
if(other.CompareTag("SpawnPoint")){
if(other.GetComponent<RoomSpawner>().spawned == false && spawned == false){
// spawns walls blocking off any opening !
Instantiate(templates.closedRoom, transform.position, Quaternion.identity);
Destroy(gameObject);
}
spawned = true;
}
}
}
}
房间模板
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RoomTemplates : MonoBehaviour
{
public GameObject[] bottomRooms;
public GameObject[] topRooms;
public GameObject[] leftRooms;
public GameObject[] rightRooms;
public GameObject closedRoom;
}
我对一个只有 1 个出生点的房间进行了新测试。我在创建第二个生成点的第二秒暂停了游戏,因此您可以看到创建的第二个关卡的高度与起始关卡的高度不同。
在下方,您可以看到连接房间在起始房间的上方生成。通过这样做,它会弄乱所有其他房间。
相反,我希望它是这样的