【发布时间】:2019-02-06 18:29:36
【问题描述】:
我目前正在 Unity 中开发一款游戏,我希望在触摸屏范围之外随机生成对象,并根据它们生成的屏幕一侧(左、右、上方或屏幕下方随机)。如果它们在屏幕左侧生成 -> 它们向右移动到屏幕上,如果它们在右侧生成,它们将向左移动到屏幕上,如果它们从上方生成 -> 它们向下移动到屏幕扩展...我尝试通过从由 4 个值(上、下、左、右)组成的数组中随机选择一个字符串,然后使用 switch 语句来执行此操作,该语句将根据对象的生成位置执行不同的代码。问题是代码只从向下位置向上生成对象,而且由于某种原因,大多数时间似乎在靠近中间的特定 X 位置生成对象。有谁知道为什么会这样以及我该如何解决这个问题。
我尝试使用随机选择方法和 switch 语句,根据对象生成的屏幕特定侧分配相应的向量值
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();
}
}
}
球应该在屏幕四个边的随机位置连续生成,如果生成到左侧,则以预定义的速度向右移动到屏幕上,如果生成到右侧,则向左移动,如果生成在上方,则向下移动屏幕,如果在屏幕下方生成则向上。
【问题讨论】:
标签: c# unity3d vector game-engine