随机生成 2D 对象,但不与其他对象重叠



我正在为UNITY的学校做一个小游戏项目,特别是一个名为Rattler Race的蛇游戏的克隆。我几乎是一个完全的引擎初学者,因此我有点挣扎。我们应该制作的游戏必须有30个独特的关卡,这些关卡具有递增的复杂性,就像这样:最终关卡

我目前的主要问题是为蛇生成食物,这样它就不会与任何内壁或边界重叠。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnFood : MonoBehaviour
{
public GameObject FoodPrefab;
public Transform BorderTop;
public Transform BorderBottom;
public Transform BorderLeft;
public Transform BorderRight;
public Transform Obstacle;
Vector2 pos;
// Use this for initialization
void Start ()
{
for (int i = 0; i < 10; i++) {
Spawn();
}
}
void Spawn()
{
pos.x = Random.Range(BorderLeft.position.x + 5,BorderRight.position.x - 5);
pos.y = Random.Range(BorderBottom.position.y + 5, BorderTop.position.y - 5);
Instantiate(FoodPrefab, pos, Quaternion.identity);
}
// Update is called once per frame
void Update ()
{
}

}

当然,代码非常简单,因为目前游戏场地是空的,没有任何障碍物: 当前状态

然而,我的问题是,如果我要扩大那个微小的红色障碍物,就像这样: 大障碍

食物会在它后面生成(每个关卡有 10 个食物对象),并且不可能获得。我的想法是从一个对象("障碍")及其副本上构建关卡,我真的不知道这个想法是否合理,但我想尝试一下。

如果有任何方法或任何方法可以在位置生成食物对象,使它们不会与障碍物重叠,例如检查空间是否已经被占用或检查食物对象是否与现有障碍物相交的方法,如果有人教我,我将不胜感激,因为我现在真的很迷路。

假设你的食物正好是一个单位长,你可以有一个协程来检查食物游戏对象周围是否有东西,如果没有任何东西,你可以生成它。

public LayerMask layerMask; //Additional variable so you can control which layer you don't want to be detected in raycast
void Spawn(){
StartCoroutine(GameObjectExists());
}

IEnumerator GameObjectExists(){
do{
yield return null;
pos.x = Random.Range(BorderLeft.position.x + 5,BorderRight.position.x - 5);
pos.y = Random.Range(BorderBottom.position.y + 5, BorderTop.position.y - 5);
}while(Physics2D.OverlapCircle(new Vector2(pos), 1f, layerMask); //1f is the radius of your food gameObject.
Instantiate(FoodPrefab, pos, Quaternion.identity);
yield return null;
}

最新更新