创建三维网格两个元素,一个元素在一行,但在随机列
本文关键字:元素 一行 随机 一个 两个 创建 维网格 三维 | 更新日期: 2023-09-27 18:15:13
我已经创建了一个三维网格。我有两个独立的对象填充这个网格的空间。我想在一行中有一个对象,但是在随机选择的列上。
以前有人这样做过吗,或者有人能给我指出正确的方向吗?
我使用Unity和c#。谢谢你。
Vector3 towerSize = new Vector3(3, 3, 3);
//create grid tower
for (int x = 0; x < towerSize.x; x++)
{
for (int z = 0; z < towerSize.z; z++)
{
for (int y = 0; y < towerSize.y; y++)
{
//spawn tiles and space them
GameObject obj = (GameObject)Instantiate(tiles);
obj.transform.position = new Vector3(x * 1.2f, y * 1.2f, z * 1.2f);
//add them all to a List
allTiles.Add(obj);
obj.name = "tile " + allTiles.Count;
}
}
}
是网格的代码。我试图让两个对象在一个单一的列表移动到这些瓷砖,但随机列对象得到相同的列,当我这样做的代码:
for (int i = 0; i < allCubes.Count; i++)
{
allCubes[i].transform.position = Vector3.MoveTowards(
allCubes[i].transform.position,
allTiles[i].transform.position, 10 * Time.deltaTime);
}
然后我把这两种类型的立方体放在单独的列表中。结果更糟了。哈哈,张贴代码有帮助吗?
我知道这是一个非常古老的问题。那是一个被取消的项目。我偶然发现了它,出于好奇,我决定尝试完成这个特殊的问题,我当时有这样的麻烦。我做到了。
public Vector3 towerSize = new Vector3(3, 3, 3);
public GameObject tiles;
public GameObject randomTile;
//public variables for debugging purposes.
//no real need to be seen in inspector in final. cleaner too if they're hidden
public int randomSelectedTile;
public List<GameObject> allTiles;
void Start()
{
//create grid tower
for (int x = 0; x < towerSize.x; x++)
{
for (int z = 0; z < towerSize.z; z++)
{
for (int y = 0; y < towerSize.y; y++)
{
//spawn cubes and space them
GameObject obj = (GameObject)Instantiate(tiles);
obj.transform.position = new Vector3(x * 1.2f, y * 1.2f, z * 1.2f);
//add them all to a List
allTiles.Add(obj);
obj.name = "tile " + allTiles.Count;
}
}
}
//select a random cube in the list
randomSelectedTile = Random.Range(0, allTiles.Count);
//get the cube object to delete
GameObject deleteObj = allTiles.ElementAt(randomSelectedTile);
//spawn the random cube at the position of the cube we will delete
GameObject rndObj = (GameObject)Instantiate(randomTile);
rndObj.transform.position = deleteObj.transform.position;
//remove the element at that location
allTiles.RemoveAt(randomSelectedTile);
//insert the random cube at that element's location
allTiles.Insert(randomSelectedTile, rndObj);
//destroy the unwanted cube
Destroy(deleteObj);
}
很高兴看到你随着时间的推移进步了。以防有人会从这个解决方案中受益。我再次为我的旧事道歉。