Beispiel #1
0
    private Transform CreateHoleWallObject(List <Vector3> shapePoints = null)
    {
        var centerOfMass = MyMaths.CenterOfVectors(shapePoints);

        for (var i = 0; i < shapePoints.Count; i++)
        {
            // Set points relative to the shape center
            shapePoints[i] = shapePoints[i] - centerOfMass;
        }

        var startIndex = 1;
        var endIndex   = shapePoints.Count - 1;

        Vector3[] vertices;
        Vector2[] uv;
        Mesh      mesh;

        var holeWalls = Instantiate(_dynamicHoleWallPrefab, centerOfMass, Quaternion.identity, transform);

        holeWalls.GetComponent <MeshFilter>().mesh = mesh = new Mesh();
        holeWalls.gameObject.name = mesh.name = $"HoleWall{_holeId}";
        var num = endIndex - startIndex;

        vertices = new Vector3[num * 2];
        uv       = new Vector2[num * 2];

        int[] triangles = new int[(num + 1) * 6 * 2];

        // Triangulate band
        var bandLen = Mathf.Sqrt(shapePoints.Sum(x => x.sqrMagnitude));
        var t       = 0;

        for (int i = startIndex, k = 0; i < endIndex; i++, k++)
        {
            vertices[k]       = shapePoints[i] + Vector3.up;
            vertices[k + num] = shapePoints[i]; // + Vector3.down;

            if (i < endIndex - 1)
            {
                // CW
                triangles[t++] = k;
                triangles[t++] = k + 1;
                triangles[t++] = k + num;

                triangles[t++] = k + 1;
                triangles[t++] = k + 1 + num;
                triangles[t++] = k + num;
            }
            else // Connecting start to end
            {
                triangles[t++] = k;
                triangles[t++] = 0;
                triangles[t++] = k + num;

                triangles[t++] = 0;
                triangles[t++] = num;
                triangles[t++] = k + num;
            }

            // wallpapering the wall
            var percentageOfWall = k / (float)num;
            var c = bandLen * percentageOfWall;
            uv[k]       = new Vector2(c, 0);
            uv[k + num] = new Vector2(c, 1);
        }

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

        return(holeWalls);
    }