我正在进行的游戏中有一个需要跳跃并在障碍物下躲避的玩家。我已经用C#编写了一个随机生成器。唯一的问题是,我想要产生一系列障碍来产生我的想法。例如,而不是随机,障碍1,5,2,3等我想要障碍1,2,3,4,5,6,7,8等,按照我希望的顺序产生。不知道如何为此启动代码,有人能指出我正确的方向吗?提前谢谢!
这是我的随机示例代码。
private void Creation()
{
for(int i = 0; i < numberOfObjects; i++)
{
cObst = Random.Range(0,100);
if(cObst <= obstL)
{
obstacleQueue.Enqueue((Transform) Instantiate(obstHPrefab.transform));
if(i == 0 && start)
{
nextPos = highPos;
}
}
else if(cObst <= obstH && cObst > obstL)
{
obstacleQueue.Enqueue((Transform) Instantiate(obstLPrefab.transform));
if(i == 0 && start)
{
nextPos = lowPos;
}
}
else if(cObst <= obstC && cObst > obstH)
{
obstacleQueue.Enqueue((Transform) Instantiate(obstCPrefab.transform));
if(i == 0 && start)
{
nextPos =cPos;
}
}
else if(cObst <= obstC && cObst > obstC)
{
obstacleQueue.Enqueue((Transform) Instantiate(obstCPrefab.transform));
if(i == 0 && start)
{
nextPos =cPos;
}
}
else
{
Debug.Log ("BREAK");
}
}
}
private void Recycle(float extraZ = 0f)
{
Transform o = obstacleQueue.Dequeue();
if(o.name == obstH.name+"(Clone)")
{
nextPos = new Vector3(highPos.x,highPos.y,nextPos.z);
}
else if(o.name == obstLPrefab.name+"(Clone)")
{
nextPos = new Vector3(lowPos.x,lowPos.y,nextPos.z);
}
else
{
nextPos = new Vector3(carPos.x,carPos.y,nextPos.z);
}
nextPos += new Vector3(
0f,
0f,
Random.Range((0-minZ)+extraZ, (0-maxZ)+extraZ));
Vector3 position = nextPos;
o.localPosition = position;
obstacleQueue.Enqueue(o);
}
void Update()
{
if(curQue <= numberOfObjects && !nextCreate)
{
waitCreate = true;
if(obstacleQueue.Peek().localPosition.z - recycle > char.position.z)
{
Destroy(GameObject.Find (obstacleQueue.Peek().name));
obstacleQueue.Dequeue();
curQue++;
}
}
else
{
nextCreate = true;
StartCoroutine(Wait(0.5f));
curQue = 1;
}
}
private void GameStart()
{
nextPos = transform.localPosition;
for(int i = 0; i < numberOfObjects; i++)
{
Recycle();
}
}
IEnumerator Wait(float duration)
{
if(waitCreate)
{
waitCreate = false;
yield return new WaitForSeconds(duration); //Wait
Creation();
for(int i = 0; i < numberOfObjects; i++)
{
if(i == 0)
{
Recycle(-25f);
}
else { Recycle(); }
}
nextCreate = false;
}
}
}
答案 0 :(得分:0)
您可以在列表中指定代表障碍物的所有数字。您可以在列表中按顺序对它们进行排序,并一次迭代一个。
List<int> Obstacles = new List<int>();
使用以下内容分配它们,
Obstacles.Add(1);
Obstacles.Add(3);
Obstacles.Add(7);
然后你可以通过替换来引用它们,
CObst = Random.Range(0,100);
使用,
CObst = List [i];
答案 1 :(得分:0)
我看到你正在使用Unity。我认为你真正的问题不是关于列表或随机性,而是如何按顺序生成对象而不是同时生成所有对象。最简单的方法是将您的spawner脚本作为预制件或场景对象,再加上Coroutine来延迟/延长执行时间。该脚本将包含一个对象列表。这些对象将在检查器中设置。
public List<GameObject> objectsToSpawn;
然后你的产卵逻辑会一次产生一个,可能在等待中间的东西:
void Start()
{
StartCoroutine(SpawnAll());
}
public IEnumerator SpawnAll()
{
foreach (GameObject obj in objectsToSpawn)
{
GameObject instance = Instantiate(obj) as GameObject;
// wait for object, see below
}
}
对于延迟/等待,您可以使用时间,或等待对象变为非活动状态(如果它自动停用,就像最终会被杀死的敌人):
yield return new WaitForSeconds(20);
或:
while (instance.activeSelf)
yield return null;