随机生成具有基于产卵位置的移动方向的移动2D对象



我目前正在Unity开发一款游戏,我希望在触摸屏的范围外随机生成对象,并根据生成对象的屏幕一侧移动(屏幕的左、右、上或下随机)。如果它们在屏幕左侧繁殖->它们会向右移动到屏幕上,如果它们在右侧繁殖,它们会向左移动到屏幕,如果它们从上面派生-->,它们会向下移动到屏幕ext.…我尝试从由4个值(上、下、左、右)组成的数组中随机选择一个字符串,然后使用switch语句,该语句将根据对象的派生位置执行不同的代码。问题是,代码只从向下的位置向上生成对象,而且由于某种原因,大多数时候似乎都在靠近中间的特定X位置生成对象。有人知道为什么会这样吗?我该如何解决这个问题。

我尝试使用随机选择方法和切换语句,根据对象在上产生的屏幕的特定一侧分配相应的矢量值

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallSpawner : MonoBehaviour
{
public GameObject BallPrefab;
public float respawnTime = 1.0f;
private Vector2 screenBounds;
private string[] edges = {"up","down","left","right"};
static System.Random random = new System.Random();
private float gap = 0.4f;

// Start is called before the first frame update
void Start()
{
screenBounds = Camera.main.ScreenToWorldPoint(new           
Vector2(Screen.width, Screen.height));
StartCoroutine(BallWave());
}
private void spawnBall()
{
GameObject a = Instantiate(BallPrefab) as GameObject;
int r = random.Next(edges.Length);
string edge = edges[r];
Vector2 moveVector;

switch (edge)
{
case "up":
moveVector =  a.transform.GetComponent<CubeConstantMove>     
().moveVector;
if (moveVector.y < 0)
{
a.transform.position = new Vector2(Random.Range(-          
screenBounds.x, screenBounds.x), screenBounds.y + gap);
}
break;
case "down":
moveVector = a.transform.GetComponent<CubeConstantMove>     
().moveVector;
if (moveVector.y > 0)
{
a.transform.position = new      
Vector2(Random.Range(-     screenBounds.x, screenBounds.x), - 
screenBounds.y - gap);
}
break;
case "left":
moveVector = a.transform.GetComponent<CubeConstantMove>               
().moveVector;
if (moveVector.y < 0)
{
a.transform.position = new Vector2(-screenBounds.x - 
gap, Random.Range(-screenBounds.y, screenBounds.y));
}
break;
case "right":
moveVector = a.transform.GetComponent<CubeConstantMove>     
().moveVector;
if (moveVector.y < 0)
{
a.transform.position = new Vector2(screenBounds.x + 
gap, Random.Range(-screenBounds.y, screenBounds.y));
}
break;
default:
break;
}

//*Manipulate to respanw from just outside the confines
}
IEnumerator BallWave()
{
while (true) {
yield return new WaitForSeconds(respawnTime);
spawnBall();
}
}
}

球应该沿着屏幕的四边在随机位置连续繁殖,如果向左繁殖,则以预定义的速度向右移动到屏幕上,如果向右繁殖,则向左移动,如果在屏幕上方繁殖,则向下移动,如果屏幕下方繁殖,则向上移动。

在此处输入图像描述

当然,所有预制件都将在同一位置生成;您不需要指定一个transform.position让它们在其中生成。Instantate接受3个参数(前置、位置、旋转)。由于您只指定了第一个参数,它将在自己的变换位置生成对象。在您的情况下,这可能是(0,0,0)-这就是为什么它在屏幕中心生成。如果你想确认它,点击资产文件夹中的实际预制件,看看它的转换位置——默认情况下,这是预制件将产生的位置。同样,如果你想让它在其他地方繁殖,你必须在实例化函数中指定其中

最新更新