网格为 10x10
这是添加空格之前的原始脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GridGenerator : MonoBehaviour
{
public GameObject gridBlock;
public int gridWidth = 10;
public int gridHeight = 10;
public List<Vector3> positions = new List<Vector3>();
public List<GameObject> blocks = new List<GameObject>();
private GameObject[] wallsParents = new GameObject[4];
void Start()
{
wallsParents[0] = GameObject.Find("Top Wall");
wallsParents[1] = GameObject.Find("Left Wall");
wallsParents[2] = GameObject.Find("Right Wall");
wallsParents[3] = GameObject.Find("Bottom Wall");
GenerateGrid();
}
private void GenerateGrid()
{
for (int x = 0; x < gridWidth; x++)
{
for (int z = 0; z < gridHeight; z++)
{
GameObject block = Instantiate(gridBlock, Vector3.zero, gridBlock.transform.rotation) as GameObject;
block.transform.parent = transform;
block.transform.tag = "Block";
block.transform.localScale = new Vector3(1, 0.1f, 1);
block.transform.localPosition = new Vector3(x, 0, z);
block.GetComponent<Renderer>().material.color = new Color(241, 255, 0, 255);
if (block.transform.localPosition.x == 0)//TOP
{
positions.Add(block.transform.localPosition);
block.transform.parent = wallsParents[0].transform;
block.transform.name = "TopWall";
}
else if (block.transform.localPosition.z == 0)//LEFT
{
positions.Add(block.transform.localPosition);
block.transform.parent = wallsParents[1].transform;
block.transform.name = "LeftWall";
}
else if (block.transform.localPosition.z == gridWidth - 1)//RIGHT
{
positions.Add(block.transform.localPosition);
block.transform.parent = wallsParents[2].transform;
block.transform.name = "RightWall";
}
else if (block.transform.localPosition.x == gridHeight - 1)//BOTTOM
{
positions.Add(block.transform.localPosition);
block.transform.parent = wallsParents[3].transform;
block.transform.name = "BottomWall";
}
blocks.Add(block);
}
}
}
}
结果:4 堵墙就位:
然后我改变了这一行:
block.transform.localPosition = new Vector3(x, 0, z);
至
block.transform.localPosition = new Vector3(x * 1.5f, 0, z * 1.5f);
现在的结果是 4 面墙的位置错误:
我也需要乘以墙壁块吗?
但是,如果我已经将所有块乘以 1.5f 那么为什么墙壁块的位置没有改变 1.5f 呢?
block.transform.localPosition = new Vector3(x * 1.5f, 0, z * 1.5f);
这条线将设置localPosition.x = 1.5f * x
只影响右墙和底墙,因为对于顶墙和左墙x = 0
,乘法不会影响。
您必须更改比较以检查索引值而不是localPosition
:
if (x == 0) //TOP
if (z == 0) //LEFT
if (z == gridHeight - 1) //RIGHT
if (x == gridWidth - 1) //BOTTOM
这将在与位置无关的墙壁中添加正确的块。
希望这可以帮助 :)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句