Ejemplo n.º 1
0
    public static void CombineForAll(GameObject currentChunk, bool remove = false)
    {
        Vector3 pos = currentChunk.transform.position;

        IChunk chunk = currentChunk.GetComponent <IChunk>();

        currentChunk.transform.position = Vector3.zero;
        currentChunk.SetActive(false);

        if (uvs == null)
        {
            uvs = SetUVs.GetStandardUVs();
        }

        Block[]           blocks  = chunk.GetBlocks();
        CombineInstance[] combine = new CombineInstance[blocks.Length];

        currentChunk.GetComponents <MeshCollider>().ToList().ForEach(GameObject.Destroy);

        for (int i = 0; i < blocks.Length; i++)
        {
            combine[i].mesh      = blocks[i].Mesh;
            combine[i].transform = Matrix4x4.TRS(blocks[i].Position, Quaternion.identity, Vector3.one);
        }

        MeshFilter refMesh = currentChunk.GetComponent <MeshFilter>();


        refMesh.mesh = new Mesh();
        refMesh.mesh.CombineMeshes(combine, true);

        List <Vector2> newMeshUVs = new List <Vector2>();

        for (int i = 0; i < blocks.Length; i++)
        {
            //add new UVs based on individual block settings
            UVSetter suv      = blocks[i].UVSetter;
            float    tilePerc = 1 / UVSetter.pixelSize;
            float    umin     = tilePerc * suv.TileX;
            float    umax     = tilePerc * (suv.TileX + 1);
            float    vmin     = tilePerc * suv.TileY;
            float    vmax     = tilePerc * (suv.TileY + 1);

            for (int j = 0; j < 24; j++)
            {
                float x = Mathf.Approximately(uvs[j].x, 0f) ? umin : umax;
                float y = Mathf.Approximately(uvs[j].y, 0f) ? vmin : vmax;

                newMeshUVs.Add(new Vector2(x, y));
            }
        }

        refMesh.mesh.uv = newMeshUVs.ToArray();

        refMesh.mesh.RecalculateBounds();
        refMesh.mesh.RecalculateNormals();

        currentChunk.transform.position = pos;
        currentChunk.AddComponent <MeshCollider>();
        currentChunk.gameObject.SetActive(true);
    }