【发布时间】:2018-06-29 08:30:57
【问题描述】:
如果你能想象一个玩家永远穿越隧道的游戏。为此,我的相机是静止的,隧道向后移动以产生运动的错觉。
屏幕上总是有 3 个迷你隧道同时粘在一起,当一个移动到玩家视野之外时,会在前面生成一个新的隧道,给人一种无限的错觉。
这一切正常,除非一条隧道被删除。之后的隧道似乎停止移动一帧,导致前面的隧道在其中移动并重叠,我不知道为什么。
每条隧道的长度正好是 116.25,默认情况下第一条隧道在屏幕上。
//An array to store the pre made tunnels for easy difficulty
public GameObject[] easyTunnels;
//List of tunnels that are currently on screen
public List<GameObject> tunnels = new List<GameObject>();
float speed = 0.5f;
int level = 0;
//A list of all of the tunnels for every difficulty(only easy atm)
List<GameObject[]> levelsArray = new List<GameObject[]>();
void Start ()
{
levelsArray.Add(easyTunnels);
//Spawn 2 tunnels for a total of 3 in a row. Starting tunnel already exists
for (int i = 1; i < 3; i++)
{
int randomTunnel = Random.Range(0, easyTunnels.Length);
Vector3 startingPos = new Vector3(0, 0, 116.25f * i);
GameObject tunnel = Instantiate(easyTunnels[randomTunnel]);
tunnel.transform.position = startingPos;
tunnels.Add(tunnel);
}
}
void Update ()
{
//For each tunnel on the map
for (int i = 0; i < tunnels.Count; i++)
{
//As its moving on the z axis, get that value
Transform tunnelPos = tunnels[i].transform;
float zPos = tunnelPos.position.z;
//Each tunnel is exactly 116.25 in length
//If it reaches this, it means its off screen as the tunnel starts at 0
if (zPos < -116.25f)
{
//Get the spawn point of the new tunnel. The existing position + the length of 3 tunnels
float newZPos = zPos + 348.75f;
//Destroy this one as we dont need it anymore
Destroy(tunnels[i]);
tunnels.RemoveAt(i);
//And spawn the new one
int randomTunnel = Random.Range(0, easyTunnels.Length);
Vector3 startingPos = new Vector3(0, 0, newZPos);
GameObject tunnel = Instantiate(levelsArray[level][randomTunnel]);
tunnel.transform.position = startingPos;
tunnels.Add(tunnel);
}
//If the tunnel exists, then move it
if (tunnels[i] != null)
{
tunnelPos.position = new Vector3(tunnelPos.position.x, tunnelPos.position.y, zPos -= speed);
}
}
}
为什么要这样做?
【问题讨论】:
-
当您从列表中删除隧道 ('tunnels.RemoveAt(i);') 时,您可能需要将 i 的计数器减一,因为想象如下: tunnel[0] get删除 (i =0) 您生成一个新隧道并将其添加到屏幕(将是隧道 [3])现在在下一个循环中,它将是 i=1;但它会指向隧道[2],因为你删除了一个,所以你跳过了一个。尝试一下,看看会发生什么。如需快速检查,请尝试评论 `tunnels.Add(tunnel);这是在循环内,看看你是否得到和 IndexOutOfRangeException。
-
啊这有道理,我没有意识到列表会自动调整它的索引