如何在给定区域随机生成对象?

问题描述

所以我正在构建一个小型 Bulletgell 游戏,并且我希望敌人在给定区域的随机生成生成。我在 BoxCollider2D 的帮助下做到了这一点,一切正常,但我希望它们在实际地图之外生成,因此他们需要走在玩家所在的地图和屏幕中。我只能在 BoxCollider 的整个区域中生成它们。有没有办法确定 SpawnScript 可以使用的区域?

图中红色标记的区域应该是敌人随机生成的区域。

感谢您的帮助:)

enter image description here

这是我使用 atm 的代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Box : MonoBehavIoUr
{
public GameObject spawnedPrefab;
public BoxCollider2D spawnArea;
Vector2 maxSpawnPos;

float lastSpawnTimeS = -1;
public float spawnDelayS = 5;

// Use this for initialization
void Start()
{
    spawnArea = GetComponent<BoxCollider2D>();
    spawnArea.enabled = false; 
    maxSpawnPos = new Vector2(spawnArea.size.x / 2,spawnArea.size.y / 2);
}

// Update is called once per frame
void Update()
{
    if (lastSpawnTimeS < 0)
    {
        lastSpawnTimeS = Time.time;
        GameObject spawned = Instantiate(spawnedPrefab,Vector3.zero,Quaternion.identity) as GameObject;
        spawned.transform.parent = transform;
        Vector3 pos = new Vector3(Random.Range(-maxSpawnPos.x,maxSpawnPos.x),Random.Range(-maxSpawnPos.y,maxSpawnPos.y),0);
        spawned.transform.localPosition = pos;
    }
    else if (lastSpawnTimeS >= 0 && Time.time - lastSpawnTimeS > spawnDelayS)
    {
        lastSpawnTimeS = -1;
    }
}

}

解决方法

如果对象试图离开生成区域,它会将其重置为零。您还可以放置 if 条件如果放置在零的对象在区域内添加一些随机位置。

if (lastSpawnTimeS < 0)
{
    lastSpawnTimeS = Time.time;
    GameObject spawned = Instantiate(spawnedPrefab,Vector3.zero,Quaternion.identity) as GameObject;
    spawned.transform.parent = transform;
    Vector3 pos = new Vector3(Random.Range(-maxSpawnPos.x,maxSpawnPos.x) % spawnArea.size.x,Random.Range(-maxSpawnPos.y,maxSpawnPos.y) % spawnArea.size.y,0);
    spawned.transform.localPosition = pos;
}
else if (lastSpawnTimeS >= 0 && Time.time - lastSpawnTimeS > spawnDelayS)
{
    lastSpawnTimeS = -1;
}