从代码创建的网格没有统一的位置

Meshes created from code don't have a position unity

所以,我尝试创建一个网格,以便我可以在其上实例化对象。我检查所述命中对象(我创建的方块之一)的位置,然后将实例化对象设置到该位置。问题是,我用代码创建的方块没有位置,都设置为 0, 0, 0.

    {
        GameObject tileObject = new GameObject(string.Format("{0}, {1}", x, y));
        tileObject.transform.parent = transform;

        Mesh mesh = new Mesh();
        tileObject.AddComponent<MeshFilter>().mesh = mesh;
        tileObject.AddComponent<MeshRenderer>().material = tileMaterial;

        Vector3[] vertices = new Vector3[4];
        vertices[0] = new Vector3(x * tileSize, 0, y * tileSize);
        vertices[1] = new Vector3(x * tileSize, 0, (y +1) * tileSize);
        vertices[2] = new Vector3((x +1) * tileSize, 0, y * tileSize);
        vertices[3] = new Vector3((x +1) * tileSize, 0, (y +1) * tileSize);

        int[] tris = new int[] { 0, 1, 2, 1, 3, 2 };

        mesh.vertices = vertices;
        mesh.triangles = tris;
        mesh.RecalculateNormals();

        tileObject.layer = LayerMask.NameToLayer("Tile");
        tileObject.AddComponent<BoxCollider>();

        //var xPos = Mathf.Round(x);
        //var yPos = Mathf.Round(y);

        //tileObject.gameObject.transform.position = new Vector3(xPos , 0f, yPos);

        return tileObject;
    }```

如前所述,您的问题是您将所有图块留在位置 0,0,0 上,只将它们的顶点设置到所需的世界 space 位置。

您宁愿将顶点保留在本地,例如

// I would use the offset of -0.5f so the mesh is centered at the transform pivot
// Also no need to recreate the arrays everytime, you can simply reference the same ones
private readonly Vector3[] vertices = new Vector3[4]
{
    new Vector3(-0.5f, 0, -0.5f);
    new Vector3(-0.5f, 0, 0.5f);
    new Vector3(0.5f, 0, -0.5f);
    new Vector3(0.5f, 0, 0.5f);
};

private readonly int[] tris = new int[] { 0, 1, 2, 1, 3, 2 };

然后在你的方法中做

GameObject tileObject = new GameObject($"{x},{y}");
tileObject.transform.parent = transform;
tileObject.localScale = new Vector3 (tileSize, 1, tileSize);
tileObject.localPosition = new Vector3(x * tileSize, 0, y * tileSize);

后者当然取决于您的需要。实际上,我更希望让这些图块也以网格对象为中心,例如

// The "-0.5f" is for centering the tile itself correctly 
// The "-gridWith/2f" makes the entire grid centered around the parent
tileObject.localPosition = new Vector3((x - 0.5f - gridWidth/2f) * tileSize, 0, (y - 0.5f - gridHeight/2f) * tileSize);

为了稍后找出你站在哪个瓦片上(例如通过光线投射、碰撞等),我宁愿使用专用组件并简单地告诉它它的坐标,例如

// Note that Tile is a built-in type so you would want to avoid confusion
public class MyTile : MonoBehaviour
{
    public Vector2Int GridPosition;
}

然后在生成网格时您只需添加

var tile = tileObject.AddComponent<MyTile>();
tile.GridPosition = new Vector2Int(x,y);

虽然您仍然可以访问其 transform.position 以获取真实世界 space 方块的中心