[英]How can i spawn Objects randomly in a given area?
So im building a small Bulletgell game, and im at the point where I want Enemys to spawn in at random Spawnpoints in a given area.因此,我正在构建一个小型 Bulletgell 游戏,并且我希望敌人在给定区域的随机 Spawnpoints 中生成。 I did that with help of the BoxCollider2D, everything works fine but I want them to spawn OUTSIDE the actuall Map so they need to walk in the Map and Screen where the Player is.我在 BoxCollider2D 的帮助下做到了这一点,一切正常,但我希望它们在实际 Map 之外生成,因此他们需要走进 Map 和播放器所在的屏幕。 I just can spawn them in the whole are of the BoxCollider.我可以在整个 BoxCollider 中生成它们。 Is there a way to determine which area the SpawnScript can use?有没有办法确定 SpawnScript 可以使用哪个区域?
In the Picture the red marked area should be the area where the Enemy spawn randomly.在图片中,红色标记的区域应该是敌人随机生成的区域。
Heres the code im using atm:这是我使用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 object tries to go outside spawn area it will reset it to zero.如果 object 尝试 go 超出生成区域,它将重置为零。 You can also place if condition if object placed at zero add some random position within area.如果 object 置于零,您也可以在区域内添加一些随机 position。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.