// Update is called once per frame void Update() { if (!Application.isPlaying) { triangulator = new Triangulator (); Vector2[] vertex = polyCollider.points; triangulator.UpdatePoints (vertex); int[] index = triangulator.Triangulate (); Vector3[] vertex3D = new Vector3[vertex.Length]; for (int i = 0; i < vertex.Length; i++) { vertex3D [i] = vertex [i]; } Vector2[] uvs = new Vector2[vertex.Length]; for (int i=0; i < uvs.Length; i++) { uvs [i] = new Vector2 (vertex [i].x, vertex [i].y); } Mesh msh = new Mesh (); msh.vertices = vertex3D; msh.triangles = index; msh.uv = uvs; msh.RecalculateBounds (); msh.RecalculateNormals (); mshFilter.mesh = msh; } }
public void FillShape() { meshRenderer.enabled = true; Mesh mesh = new Mesh(); Vector2[] points = polygonCollider2D.points; Vector3[] vertices = new Vector3[ polygonCollider2D.GetTotalPointCount() ]; for( int j=0; j < polygonCollider2D.GetTotalPointCount(); j++ ) { Vector2 actual = points[ j ]; vertices[ j ] = new Vector3( actual.x, actual.y, 1 ); } Triangulator tr = new Triangulator( points ); int [] triangles = tr.Triangulate(); mesh.vertices = vertices; mesh.triangles = triangles; MeshFilter mf = GetComponent<MeshFilter>(); if( !mf ) { mf = gameObject.AddComponent<MeshFilter>(); } mf.mesh = mesh; }
public void meshInit() { Vector2[] vertices = new Vector2[points.Count + 4]; int j = 0; for (; j < points.Count; j++) { Point p = points[j]; double x = centre - Math.Cos (p.getTheta()) * p.getRad(); double y = -Camera.main.orthographicSize - Camera.main.orthographicSize * 0.05d + (Math.Sin (p.getTheta()) * p.getRad()); vertices[j] = new Vector2((float)x,(float) y); } vertices [j++] = new Vector2 ((float)+ size,(float) -size); vertices [j++] = new Vector2 ((float)size, (float)size); vertices [j++] = new Vector2 ((float)- size, (float)size); vertices [j++] = new Vector2 ((float)- size, (float)- size); Triangulator t = new Triangulator (vertices); int[] indices = t.Triangulate (); Vector3[] v3 = new Vector3[vertices.Length]; for (int i = 0; i < v3.Length; i++) { v3[i] = new Vector3(vertices[i].x, vertices[i].y, 0); } Mesh m = new Mesh (); m.vertices = v3; m.triangles = indices; m.RecalculateNormals (); m.RecalculateBounds (); //Add to stuff this.GetComponent<MeshFilter> ().mesh = m; }
private void Awake() { mf = GetComponent<MeshFilter>(); if (mf != null) { //modify collider points to snipping tringle //poll.points Vector2[] vert2d = new Vector2[mf.mesh.vertexCount]; for (int v = 0; v < mf.mesh.vertexCount; v++) { vert2d[v] = new Vector2(mf.mesh.vertices[v].x, mf.mesh.vertices[v].y); } Triangulator tr = new Triangulator(vert2d); int[] indices = tr.Triangulate(); Vector3[] vertices = new Vector3[indices.Length]; for (int i = 0; i < vertices.Length; i++) { vertices[i] = new Vector3(vertices[i].x, vertices[i].y, 0); } // Create the mesh Mesh msh = mf.mesh; msh.vertices = vertices; msh.triangles = indices; msh.RecalculateNormals(); msh.RecalculateBounds(); mf.mesh = msh; // mesh.mesh.triangles = newTriangles; } }
void Start () { int pointCount = 0; PolygonCollider2D pc2 = gameObject.GetComponent<PolygonCollider2D>(); pointCount = pc2.GetTotalPointCount(); MeshFilter mf = GetComponent<MeshFilter>(); Mesh mesh = new Mesh(); Vector2[] points = pc2.points; Vector3[] vertices = new Vector3[pointCount]; for(int j=0; j<pointCount; j++){ Vector2 actual = points[j]; vertices[j] = new Vector3(actual.x, actual.y, 0); } Triangulator tr = new Triangulator(points); int [] triangles = tr.Triangulate(); mesh.vertices = vertices; mesh.triangles = triangles; mf.mesh = mesh; }
public void updateMesh() { mesh = GetComponent<MeshFilter> ().mesh; edgeCollider = GetComponent<EdgeCollider2D> (); meshBkgFilter = gameObject.transform.Find ("Background").GetComponent<MeshFilter> (); meshBkg = meshBkgFilter.mesh; float x = 0; float y = 0; float z = (float) gameObject.transform.position.z; if (relativePosition) { x = (float) gameObject.transform.position.x; y = (float) gameObject.transform.position.y; } // Use the triangulator to get indices for creating triangles Triangulator tr = new Triangulator(vertices); int[] indices = tr.Triangulate(); // Create the Vector3 and collider vertices Vector3[] vertices3 = new Vector3[vertices.Length]; Vector2[] points = new Vector2[vertices.Length]; for (int i=0; i<vertices.Length; i++) { vertices3[i] = new Vector3(x + vertices[i].x, y + vertices[i].y, z); points[i] = new Vector2(x + vertices[i].x, y + vertices[i].y); } Vector2[] uvs = new Vector2[vertices3.Length]; int i2 = 0; while (i2 < uvs.Length) { uvs[i2] = new Vector2(vertices3[i2].x, vertices3[i2].z); i2++; } edgeCollider.points = points; mesh.vertices = vertices3; mesh.triangles = indices; mesh.uv = uvs; mesh.RecalculateNormals(); mesh.RecalculateBounds(); //Background (reverse terrain) meshBkg.vertices = vertices3; meshBkg.triangles = indices; meshBkg.uv = uvs; meshBkg.RecalculateNormals(); meshBkg.RecalculateBounds(); ReverseNormals (meshBkgFilter); }
void MESH_init() { // Create Vector2 vertices vertices2D = new List<Vector2> (); vertices2D.Add (new Vector2 (0, 0)); vertices2D.Add (new Vector2 (-FOV_length * .5f, FOV_width)); vertices2D.Add (new Vector2 (0, FOV_width)); vertices2D.Add (new Vector2 (FOV_length * .5f, FOV_width)); // Use the triangulator to get indices for creating triangles Triangulator tr = new Triangulator (vertices2D); trias = tr.Triangulate (); // Create the Vector3 vertices verts = new Vector3[vertices2D.Count]; for (int i=0; i<verts.Length; i++) { verts [i] = new Vector3 (vertices2D [i].x, 0, vertices2D [i].y); } // Create the mesh mesh = new Mesh (); mesh.vertices = verts; mesh.triangles = trias; mesh.uv = vertices2D.ToArray (); mesh.RecalculateNormals (); mesh.RecalculateBounds (); if (mat == null) { mat = new Material (Shader.Find ("Transparent/Diffuse")); //mat.mainTexture = texture; Color c = Color.green; c = new Color(c.r,c.g,c.b,.2f); mat.color = c; //new Color(1,.5f,0,.5f); } meshRenderer = (MeshRenderer)gameObject.GetComponent (typeof(MeshRenderer)); if (meshRenderer == null) meshRenderer = (MeshRenderer)gameObject.AddComponent (typeof(MeshRenderer)); meshFilter = (MeshFilter)gameObject.GetComponent (typeof(MeshFilter)); if (meshFilter == null) meshFilter = (MeshFilter)gameObject.AddComponent (typeof(MeshFilter)); meshFilter.mesh = mesh; meshRenderer.material = mat; meshCollider = (MeshCollider)gameObject.GetComponent (typeof(MeshCollider)); if (meshCollider == null) { meshCollider = (MeshCollider)gameObject.AddComponent (typeof(MeshCollider)); } meshCollider.sharedMesh = mesh; meshCollider.isTrigger = true; }
void Start() { switch (gameObject.GetComponent<PlayerController> ().playerType) { case 0: pc2 = squareCollider; break; case 1: //pc2 = circleCollider; gameObject.GetComponent<MeshRenderer>().enabled = false; break; case 2: pc2 = triangleCollider; break; case 3: pc2 = trapezoidCollider; break; case 4: pc2 = rectangleCollider; break; case 5: pc2 = starCollider; break; } // don't act if type is circle if (gameObject.GetComponent<PlayerController> ().playerType != 1){ //Render thing int pointCount = 0; pointCount = pc2.GetTotalPointCount(); MeshFilter mf = GetComponent<MeshFilter>(); Mesh mesh = new Mesh(); Vector2[] points = pc2.points; Vector3[] vertices = new Vector3[pointCount]; for(int j=0; j<pointCount; j++){ Vector2 actual = points[j]; vertices[j] = new Vector3(actual.x, actual.y, 0); } Triangulator tr = new Triangulator(points); int [] triangles = tr.Triangulate(); mesh.vertices = vertices; mesh.triangles = triangles; mf.mesh = mesh; //Render thing } }
private int[] GetMeshTriangles() { List<Vector2> vertices = new List<Vector2>(); foreach (Vector3 v in _PlanetVertices) { vertices.Add((Vector2) v); } Triangulator triangulator = new Triangulator(vertices.ToArray()); //TODO: hack, trying to reuse me cast PolygonCollider2D col = gameObject.AddComponent<PolygonCollider2D>(); col.SetPath(0, vertices.ToArray()); return triangulator.Triangulate(); }
public static Mesh CreateMesh(Vector2[] poly) { Triangulator triangulator = new Triangulator(poly); int[] tris = triangulator.Triangulate(); Mesh m = new Mesh(); Vector3[] vertices = new Vector3[poly.Length * 2]; for (int i = 0; i < poly.Length; i++) { vertices[i].x = poly[i].x; vertices[i].y = poly[i].y; vertices[i].z = -10; vertices[i + poly.Length].x = poly[i].x; vertices[i + poly.Length].y = poly[i].y; vertices[i + poly.Length].z = 10; } int[] triangles = new int[tris.Length * 2 + poly.Length * 6]; int count_tris = 0; for (int i = 0; i < tris.Length; i += 3) { triangles[i] = tris[i]; triangles[i + 1] = tris[i + 1]; triangles[i + 2] = tris[i + 2]; } count_tris += tris.Length; for (int i = 0; i < tris.Length; i += 3) { triangles[count_tris + i] = tris[i + 2] + poly.Length; triangles[count_tris + i + 1] = tris[i + 1] + poly.Length; triangles[count_tris + i + 2] = tris[i] + poly.Length; } count_tris += tris.Length; for (int i = 0; i < poly.Length; i++) { int n = (i + 1) % poly.Length; triangles[count_tris] = i; triangles[count_tris + 1] = i + poly.Length; triangles[count_tris + 2] = n; triangles[count_tris + 3] = n; triangles[count_tris + 4] = n + poly.Length; triangles[count_tris + 5] = i + poly.Length; count_tris += 6; } m.vertices = vertices; m.triangles = triangles; m.RecalculateNormals(); m.RecalculateBounds(); m.Optimize(); return m; }
// Use this for initialization void Start() { // Create the vertices of the plant List<Vector2> vertices2D = new List<Vector2>(); int halfPoints = NUMBER_OF_VERTICES / 2; // Number of points for one side of the plant for (int i = 0; i < NUMBER_OF_VERTICES; i++) { int sideFactor = i < halfPoints ? 1 : -1; // This factor helps to draw the plant with one single stroke float percentOfCompletion = ((float)(i % halfPoints)) / ((float)halfPoints - 1f); // Percentage of completion of a single side if(sideFactor > 0) // Right side of the plant vertices2D.Add(new Vector2(shaftCurve.Evaluate(percentOfCompletion) * width * sideFactor, heigth * percentOfCompletion)); else // Left side of the plant vertices2D.Add(new Vector2(shaftCurve.Evaluate(1 - percentOfCompletion) * width * sideFactor, heigth * (1 - percentOfCompletion))); } // Use the triangulator to get indices for creating triangles Triangulator tr = new Triangulator(vertices2D.ToArray()); int[] indices = tr.Triangulate(); // Create the Vector3 vertices Vector3[] vertices = new Vector3[vertices2D.Count]; for (int i = 0; i < vertices.Length; i++) { vertices[i] = new Vector3(vertices2D[i].x, vertices2D[i].y, 0); } // Create the mesh Mesh msh = new Mesh(); msh.vertices = vertices; msh.triangles = indices; Vector2[] uvs = new Vector2[vertices.Length]; for (int i = 0; i < uvs.Length; i++) { uvs[i] = new Vector2(vertices[i].x, vertices[i].z); } msh.uv = uvs; msh.RecalculateNormals(); msh.RecalculateBounds(); msh.Optimize(); // Set up game object with mesh; MeshFilter filter = GetComponent<MeshFilter>(); filter.mesh = msh; }
public static void create(string name, List<Vector2> verticesList) { GameObject obstacle = new GameObject (name, typeof(MeshFilter), typeof(MeshRenderer)); MeshFilter mesh_filter = obstacle.GetComponent<MeshFilter> (); obstacle.transform.position = new Vector3 (0, 0.01f, 0); var renderer = obstacle.GetComponent<Renderer>(); renderer.sharedMaterial = new Material (Shader.Find ("Transparent/Diffuse")); renderer.sharedMaterial.color = new Color (1, 0, 0, .3f); Vector2[] vertices2D = verticesList.ToArray(); // Use the triangulator to get indices for creating triangles Triangulator tr = new Triangulator(vertices2D); int[] indicesArray = tr.Triangulate(); List<int> indices = new List<int>(); for (int i = 0;i<indicesArray.Length;i++) { indices.Add (indicesArray[i]); } // Create the Vector3 vertices List<Vector3> vertices = new List<Vector3>(); for (int i=0; i<vertices2D.Length; i++) { vertices.Add (new Vector3(vertices2D[i].x, 0, vertices2D[i].y)); } // Create the mesh Mesh mesh = new Mesh(); mesh.vertices = vertices.ToArray(); mesh.uv = verticesList.ToArray(); mesh.triangles = indices.ToArray(); mesh.RecalculateNormals(); mesh.RecalculateBounds(); //flip if needed if (mesh.normals [0].y == -1) { indices.Reverse (); mesh.triangles = indices.ToArray (); mesh.RecalculateNormals(); } mesh_filter.mesh = mesh; GeometryLoader gl = GameObject.Find ("GeometryLoader").GetComponent<GeometryLoader> (); gl.setWorldAsParent (obstacle); }
public void Generate() { // Create Vector2 vertices Vector2[] vertices2D = new Vector2[] { }; foreach (Vector3 point in points) { point_pos.Add(new Vector2(point.x,point.z)); } vertices2D = point_pos.ToArray(); // Use the triangulator to get indices for creating triangles Triangulator tr = new Triangulator(vertices2D); int[] indices = tr.Triangulate(); // Create the Vector3 vertices Vector3[] vertices = new Vector3[vertices2D.Length]; for (int i = 0; i < vertices.Length; i++) { vertices[i] = new Vector3(vertices2D[i].x, 0, vertices2D[i].y); } // Create the mesh Mesh msh = new Mesh(); msh.vertices = vertices; msh.triangles = indices; msh.RecalculateNormals(); msh.RecalculateBounds(); // Set up game object with mesh; if(gameObject.GetComponent<MeshRenderer>() == null) { gameObject.AddComponent<MeshRenderer>(); gameObject.AddComponent<MeshFilter>(); } MeshFilter filter = gameObject.GetComponent<MeshFilter> (); filter.mesh = msh; Mesh mesh = GetComponent<MeshFilter>().mesh; Vector3[] UVvertices = mesh.vertices; Vector2[] uvs = new Vector2[vertices.Length]; for (int i = 0; i < uvs.Length; i++) { uvs[i] = new Vector2(UVvertices[i].x / 10, UVvertices[i].z / 10); } mesh.uv = uvs; }
public void UpdateMesh() { var poly = GetComponent<PolygonCollider2D>(); var tris = new Triangulator(poly.points); var indices = tris.Triangulate(); Mesh mesh = new Mesh(); Vector3[] points3 = new Vector3[poly.points.Length]; for (int i = 0; i < poly.points.Length; i++) points3[i] = poly.points[i]; Vector2[] uv = new Vector2[poly.points.Length]; for (int i = 0; i < poly.points.Length; i++) uv[i] = transform.TransformPoint(poly.points[i]); mesh.vertices = points3; mesh.uv = uv; mesh.triangles = indices; GetComponent<MeshFilter>().mesh = mesh; }
void Start() { // Create Vector2 vertices Vector2[] vertices2D = new Vector2[] { new Vector2(0,0), new Vector2(0,50), new Vector2(50,50), new Vector2(50,100), new Vector2(0,100), new Vector2(0,150), new Vector2(150,150), new Vector2(150,100), new Vector2(100,100), new Vector2(100,50), new Vector2(150,50), new Vector2(150,0), }; // Use the triangulator to get indices for creating triangles Triangulator tr = new Triangulator(vertices2D); int[] indices = tr.Triangulate(); // Create the Vector3 vertices Vector3[] vertices = new Vector3[vertices2D.Length]; for (int i = 0; i < vertices.Length; i++) { vertices[i] = new Vector3(vertices2D[i].x, vertices2D[i].y, 0); } // Create the mesh Mesh msh = new Mesh(); msh.vertices = vertices; msh.triangles = indices; msh.RecalculateNormals(); msh.RecalculateBounds(); // Set up game object with mesh; gameObject.AddComponent(typeof(MeshRenderer)); MeshFilter filter = gameObject.AddComponent(typeof(MeshFilter)) as MeshFilter; filter.mesh = msh; }
public void CreateMesh(Vector2[] newPoints, Material material) { // Use the triangulator to get indices for creating triangles Triangulator tr = new Triangulator(newPoints); int[] indices = tr.Triangulate(); // Create the Vector3 vertices Vector3[] vertices = new Vector3[newPoints.Length]; for (int i=0; i<vertices.Length; i++) { vertices[i] = new Vector3(newPoints[i].x, newPoints[i].y, 0); } // Create the New Mesh this.mesh = new Mesh(); mesh.vertices = vertices; mesh.triangles = indices; mesh.RecalculateNormals(); mesh.RecalculateBounds(); //Set up texture coordinate for New Mesh Vector2[] uvs = new Vector2[vertices.Length]; for(int i = 0; i<uvs.Length; i++){ uvs[i] = new Vector2(vertices[i].x, vertices[i].y); } mesh.uv = uvs; // Set up game object with mesh; if(GetComponent<MeshRenderer>()==null) gameObject.AddComponent(typeof(MeshRenderer)); if(GetComponent<MeshFilter>()==null) gameObject.AddComponent(typeof(MeshFilter)); MeshFilter filter = GetComponent<MeshFilter>() as MeshFilter; filter.mesh = this.mesh; MeshRenderer mRenderer = GetComponent<MeshRenderer>() as MeshRenderer; mRenderer.material = material; //NOTE HARD CODING !!! mRenderer.sortingLayerName = "Foreground"; }
/// <summary> /// Sets the collider2D according to an array of vector3s /// </summary> /// <param name="vertices">The vector3 vertex locations of the district shape</param> public void SetCollider(Vector3[] vertices) { Vector2[] temp = new Vector2[vertices.Length]; Vector3 tempTemp; for (int i = 0; i < vertices.Length; i++) { //take just the relevant x and z coordinates... temp[i] = new Vector2(vertices[i].x, vertices[i].z); //And now we have to transform them into local coordinates, for use in the collider tempTemp = new Vector3(temp[i].x, 0, temp[i].y); tempTemp = this.transform.InverseTransformPoint(tempTemp); temp[i] = new Vector2(tempTemp.x, tempTemp.z); } //area.points = temp; Triangulator triangluator = new Triangulator (temp); mesh.triangles = triangluator.Triangulate (); mesh.RecalculateNormals (); //this.gameObject.AddComponent<MeshCollider>(mesh); MeshCollider mCol = this.gameObject.AddComponent<MeshCollider> (); mCol.sharedMesh = mesh; //mCol.isTrigger = true; }
void CreatePolygon() { // Use the triangulator to get indices for creating triangles Triangulator tr = new Triangulator(vertices2D); int[] indices = tr.Triangulate(); // Create the Vector3 vertices Vector3[] vertices = new Vector3[vertices2D.Length]; for (int i=0; i<vertices.Length; i++) { vertices[i] = new Vector3(vertices2D[i].x, 0.0f, vertices2D[i].y); } // Create the mesh Mesh msh = new Mesh(); msh.vertices = vertices; msh.triangles = indices; msh.RecalculateNormals(); msh.RecalculateBounds(); // Set up game object with mesh; MeshFilter filter = gameObject.GetComponent(typeof(MeshFilter)) as MeshFilter; filter.mesh = msh; }
Mesh buildMesh(params Vector2[] points) { // Use the triangulator to get indices for creating triangles Triangulator tr = new Triangulator(points); int[] indices = tr.Triangulate(); // Create the Vector3 vertices Vector3[] vertices = new Vector3[points.Length]; for (int i = 0; i < vertices.Length; i++) { vertices[i] = new Vector3(points[i].x, points[i].y, 0); } // Create the mesh Mesh msh = new Mesh(); msh.vertices = vertices; msh.triangles = indices; msh.RecalculateNormals(); msh.RecalculateBounds(); MeshFilter mf = GetComponent<MeshFilter>(); mf.mesh = msh; return msh; }
void CreatePolygon() { string objectName = "Polygon"; Mesh mesh = new Mesh (); Vector3[] vertices = new Vector3[cubeIndex]; for (int i=0; i<cubeIndex; i++) { vertices [i] = cubeList [i].transform.position; } mesh.vertices = vertices; Vector2[] verticesXY = new Vector2[cubeIndex]; for (int i=0; i<cubeIndex; i++) { Vector3 pos = cubeList [i].transform.position; verticesXY [i] = new Vector2 (pos.x, pos.y); } Triangulator tr = new Triangulator (verticesXY, Camera.mainCamera.transform.position); int[] indices = tr.Triangulate (); mesh.triangles = indices; // UVデータの設定は今回は省略 mesh.uv = new Vector2[cubeIndex]; mesh.RecalculateNormals (); // 法線の再計算 mesh.RecalculateBounds (); // バウンディングボリュームの再計算 mesh.Optimize (); GameObject newGameobject = new GameObject (objectName); MeshRenderer meshRenderer = newGameobject.AddComponent<MeshRenderer> (); meshRenderer.material = polygonMaterial; //meshRenderer.material.mainTexture = (Texture)Instantiate (Resources.Load ("Image2")); MeshFilter meshFilter = newGameobject.AddComponent<MeshFilter> (); meshFilter.mesh = mesh; }
public void CalculateVerts() { mesh.Clear(); // Use the triangulator to get indices for creating triangles ConstrainVertsToLimter(); Triangulator tr = new Triangulator(verts.ToVector2Array()); int[] indices = tr.Triangulate(); Vector2[] uvs = new Vector2[verts.Length]; for (int i=0; i < uvs.Length; i++) { uvs[i] = new Vector2(verts[i].x, verts[i].z); } mesh.vertices = verts; mesh.uv = uvs; mesh.triangles = indices; mesh.RecalculateNormals(); mesh.RecalculateBounds(); mesh.Optimize(); polyColl.points = verts.ToVector2Array(); }
public static Mesh CreateMesh(Vector2[] poly, float extrusion) { // convert polygon to triangles Triangulator triangulator = new Triangulator(poly); int[] tris = triangulator.Triangulate(); Mesh m = new Mesh(); Vector3[] vertices = new Vector3[poly.Length * 2]; for (int i = 0; i < poly.Length; i++) { vertices[i].x = poly[i].x; vertices[i].y = poly[i].y; vertices[i].z = -extrusion; // front vertex vertices[i + poly.Length].x = poly[i].x; vertices[i + poly.Length].y = poly[i].y; vertices[i + poly.Length].z = extrusion; // back vertex } int[] triangles = new int[tris.Length * 2 + poly.Length * 6]; int count_tris = 0; for (int i = 0; i < tris.Length; i += 3) { triangles[i] = tris[i]; triangles[i + 1] = tris[i + 1]; triangles[i + 2] = tris[i + 2]; } // front vertices count_tris += tris.Length; for (int i = 0; i < tris.Length; i += 3) { triangles[count_tris + i] = tris[i + 2] + poly.Length; triangles[count_tris + i + 1] = tris[i + 1] + poly.Length; triangles[count_tris + i + 2] = tris[i] + poly.Length; } //texture coordinate Vector2[] uvs = new Vector2[vertices.Length]; for (int i = 0; i < uvs.Length; i++) { uvs[i] = new Vector2(vertices[i].x, vertices[i].z); } m.vertices = vertices; m.triangles = triangles; m.uv = uvs; m = Triangulator.SideExtrusion(m); m.RecalculateNormals(); m.RecalculateBounds(); UnityEditor.MeshUtility.Optimize(m); return(m); }
private void CreateGroundArea(Way w) { Vector3[] nodes = new Vector3[w.nodes.Count]; Vector2[] xz = new Vector2[w.nodes.Count]; float height = 0; if (w.height != 0) height = w.height; Vector3 centroid = new Vector3(); for (int a = 0; a < w.nodes.Count; a++) { RaycastHit hit; Node n = w.nodes[a]; nodes[a] = new Vector3((float)((n.easthing - offsetPositionX) / precision), 5000, (float)((n.northing - offsetPositionZ) / precision)); if (Physics.Raycast(nodes[a], -Vector3.up, out hit, Mathf.Infinity, layerMask)) { nodes[a].y = hit.point.y + height + 0.5f; } else { nodes[a].y = 1; } xz[a] = new Vector2((float)((n.easthing - offsetPositionX) / precision), (float)((n.northing - offsetPositionZ) / precision)); centroid += nodes[a]; } centroid /= w.nodes.Count; centroid.y += 1; // Vector3 position = new Vector3(centroid.x, 5000, centroid.z); float baseHeight = 0; /*RaycastHit hit; if (Physics.Raycast(position, -Vector3.up, out hit, Mathf.Infinity, layerMask)) { baseHeight = hit.point.y; }*/ //centroid = new Vector3(centroid.x, centroid.y + baseHeight, centroid.z); GameObject build = new GameObject(); //build.transform.position = new Vector3(0, centroid.y, 0); build.name = w.id.ToString(); mapManager.mapHash.Add(w.id); wayList.Add(w.id); build.isStatic = true; build.transform.parent = this.transform; GameObject roof = new GameObject(); // roof.transform.position = new Vector3(0, centroid.y, 0); roof.name = (2 * w.id).ToString(); mapManager.mapHash.Add(2 * w.id); wayList.Add(2 * w.id); roof.isStatic = true; if (w.name != null) { GameObject label = new GameObject(); FloatingLabel lb = label.AddComponent<FloatingLabel>(); lb.text = w.name; lb.transform.position = centroid; lb.target = GameObject.FindGameObjectWithTag("Player").transform; label.transform.parent = build.transform; } roof.transform.parent = build.transform; Vector2[] xzRoof = new Vector2[w.nodes.Count - 1]; for (int a = 0; a < xzRoof.Length; a++) { xzRoof[a] = xz[a]; } Triangulator tr = new Triangulator(xzRoof); int[] indices = tr.Triangulate(); // Create the mesh Mesh roofm = new Mesh(); roofm.vertices = nodes; roofm.triangles = indices; Vector2[] uvs = new Vector2[nodes.Length]; for (int a = 0; a < nodes.Length; a++) { if (a < nodes.Length - 1) { uvs[a] = new Vector2(Mathf.Abs(nodes[a].x) / nodes[nodes.Length - 1].x, Mathf.Abs(nodes[a].z) / nodes[nodes.Length - 1].x); } else { uvs[a] = new Vector2(1, 1); } } roofm.uv = uvs; roofm.RecalculateNormals(); roofm.RecalculateBounds(); roof.AddComponent(typeof(MeshRenderer)); MeshFilter filter2 = roof.AddComponent(typeof(MeshFilter)) as MeshFilter; roof.AddComponent<MeshCollider>(); filter2.mesh = roofm; if (w.type == WayType.Parking) roof.GetComponent<MeshRenderer>().material = Resources.Load("Materials/Parking Material") as Material; if (w.type == WayType.Park) roof.GetComponent<MeshRenderer>().material = Resources.Load("Materials/Park Material") as Material; if (w.type == WayType.RiverBank) roof.GetComponent<MeshRenderer>().material = Resources.Load("Materials/River Material") as Material; roof.transform.parent = transform; }
public static Mesh CreateMesh(Vector2[] poly, float extrusion) { Array.Resize <Vector2>(ref poly, poly.Length - 1); // convert polygon to triangles Triangulator triangulator = new Triangulator(poly, false); //Triangulator triangulator = new Triangulator(poly); int[] tris = triangulator.Triangulate(); Mesh m = new Mesh(); Vector3[] vertices = new Vector3[poly.Length * 2]; for (int i = 0; i < poly.Length; i++) { vertices[i].x = poly[i].x; vertices[i].y = 0.0f; vertices[i].z = poly[i].y; // front vertex vertices[i + poly.Length].x = poly[i].x; vertices[i + poly.Length].y = extrusion; vertices[i + poly.Length].z = poly[i].y; // back vertex } int[] triangles = new int[tris.Length]; int count_tris = 0; // If we want to render the underneath //for (int i = 0; i < tris.Length; i += 3) //{ // triangles[i] = tris[i]; // triangles[i + 1] = tris[i + 2]; // triangles[i + 2] = tris[i + 1]; //} // front vertices //count_tris += tris.Length; for (int i = 0; i < tris.Length; i += 3) { triangles[count_tris + i] = tris[i + 1] + poly.Length; triangles[count_tris + i + 1] = tris[i + 2] + poly.Length; triangles[count_tris + i + 2] = tris[i] + poly.Length; } //texture coordinate Vector2[] uvs = new Vector2[vertices.Length]; for (int i = 0; i < uvs.Length; i++) { uvs[i] = new Vector2(vertices[i].x, vertices[i].z); } m.vertices = vertices; m.triangles = triangles; m.uv = uvs; m = Triangulator.SideExtrusion(m, IsClockwise(poly)); m.RecalculateNormals(); m.RecalculateBounds(); return(m); }
void CreateMesh() { switch (type) { case eMeshType.TMesh: vertices2D = new Vector2[] { new Vector2(0, 0), new Vector2(0, 50), new Vector2(50, 50), new Vector2(50, 100), new Vector2(0, 100), new Vector2(0, 150), new Vector2(150, 150), new Vector2(150, 100), new Vector2(100, 100), new Vector2(100, 50), new Vector2(150, 50), new Vector2(150, 0), }; break; case eMeshType.BoxClock: vertices2D = new Vector2[] { new Vector2(0, 0), new Vector2(0, 50), new Vector2(50, 50), new Vector2(50, 0) }; break; case eMeshType.BoxAntiClock: vertices2D = new Vector2[] { new Vector2(0, 0), new Vector2(50, 0), new Vector2(50, 50), new Vector2(0, 50) }; break; case eMeshType.PolygonClock: vertices2D = new Vector2[] { new Vector2(10, 0), new Vector2(0, 50), new Vector2(50, 50), new Vector2(40, 0) }; break; case eMeshType.PolygonAntiClock: vertices2D = new Vector2[] { new Vector2(0, 0), new Vector2(10, 50), new Vector2(40, 50), new Vector2(50, 0) }; break; } // Use the triangulator to get indices for creating triangles Triangulator tr = new Triangulator(vertices2D); int[] _triangles = tr.Triangulate(); // Create the Vector3 vertices Vector3[] _vertices = new Vector3[vertices2D.Length]; for (int i = 0; i < _vertices.Length; i++) { _vertices[i] = new Vector3(vertices2D[i].x, vertices2D[i].y, 0); } // Create the mesh mesh.Clear(); mesh.vertices = _vertices; mesh.triangles = _triangles; mesh.uv = tr.CalculateUV(); mesh.RecalculateNormals(); mesh.RecalculateBounds(); GetComponent <MeshRenderer>().material.mainTextureScale = tr.CalculateScale(10f); // Set up game object with mesh; //gameObject.AddComponent(typeof(MeshRenderer)); //MeshFilter filter = gameObject.AddComponent(typeof(MeshFilter)) as MeshFilter; }
protected void constructProcedurally() { var verticesCount = footprint.vertices.Count - 1; var vertices = footprint.vertices.GetRange(0, verticesCount); int layers = 1;// (int)(height / Config.BUILDING_LAYER_HEIGHT); System.Func <Vector3, Vector2> V3_to_V2 = v3 => new Vector2(v3.x, v3.z); // uv Vector2 uv_00 = Vector2.zero; Vector2 uv_10 = new Vector2(1f, 0f); Vector2 uv_01 = new Vector2(0f, 1f * layers); Vector2 uv_11 = new Vector2(1f, 1f * layers); // Roof Triangulator tris = new Triangulator( vertices .Select(V3_to_V2)); var indices = tris.Triangulate(); var mesh_triangles = new List <int>(indices); var mesh_vertices = new List <Vector3>(vertices .Select(v => new Vector3(v.x, height, v.z))); var mesh_uv = new List <Vector2>(mesh_vertices .Select(tri => uv_00)); // Bottom var indices_bottom = new List <int>(indices); indices_bottom.Reverse(); mesh_triangles.AddRange(indices_bottom .Select(index => correspondingVertexIndex(verticesCount, index))); mesh_vertices.AddRange(vertices); mesh_uv.AddRange(mesh_uv); // Sides for (int p = verticesCount - 1, q = 0; q < verticesCount; p = q++) { var r = correspondingVertexIndex(verticesCount, p); var s = correspondingVertexIndex(verticesCount, q); var count = 2 * verticesCount + q * 6; mesh_vertices.AddRange( new Vector3[] { mesh_vertices[r], mesh_vertices[p], mesh_vertices[q], mesh_vertices[r], mesh_vertices[q], mesh_vertices[s], }); mesh_triangles.AddRange( new int[] { count, count + 1, count + 2, count + 3, count + 4, count + 5 }); mesh_uv.AddRange( new Vector2[] { uv_00, uv_01, uv_11, uv_00, uv_11, uv_10 }); } // Meshes of the building. Mesh mesh = new Mesh(); mesh.vertices = mesh_vertices.ToArray(); mesh.triangles = mesh_triangles.ToArray(); mesh.uv = mesh_uv.ToArray(); mesh.RecalculateNormals(); mesh.RecalculateBounds(); // Set up game object with mesh. MeshFilter filter = gameObject.AddComponent <MeshFilter>(); filter.mesh = mesh; gameObject.GetComponent <MeshCollider>().sharedMesh = mesh; }
/// <summary> /// Creates a virtual platform from both top and bottom vertices. /// </summary> /// <returns>A new virtual platform from the specified vertices.</returns> /// <param name="top">The top vertices of the platform.</param> /// <param name="bottom">The bottom vertices of the platform.</param> private GameObject CreatePlatform(PlatformInput top, PlatformInput bottom) { GameObject virtualPlatform = new GameObject(); virtualPlatform.layer = LayerMask.NameToLayer("Virtual"); virtualPlatform.AddComponent <MeshFilter>(); MeshRenderer renderer = virtualPlatform.AddComponent <MeshRenderer>(); if (top.type == PlatformType.Surface) { virtualPlatform.name = "Collider"; renderer.material = surfaceMaterial; } else { virtualPlatform.name = "Virtual Platform"; renderer.material = virtualPlatformMaterial; } Mesh mesh = virtualPlatform.GetComponent <MeshFilter>().mesh; // Create the vertices of the platform. Vector3[] vertices = new Vector3[top.vertices.Count * 6]; // Used to determine clockwise/counter-clockwise. float edgeSum = 0; for (int i = 0; i < top.vertices.Count; i++) { vertices[i] = top.vertices[i]; vertices[i + top.vertices.Count] = bottom.vertices[i]; if (i < top.vertices.Count - 1) { edgeSum += (top.vertices[i + 1].x - top.vertices[i].x) * (top.vertices[i + 1].z + top.vertices[i].z); } else { edgeSum += (top.vertices[0].x - top.vertices[i].x) * (top.vertices[0].z + top.vertices[i].z); } } bool clockwise = edgeSum > 0; // Find the triangles that can make up the top and bottom faces of the platform mesh. Triangulator triangulator = new Triangulator(top.vertices.ToArray()); int[] topTriangles = triangulator.Triangulate(); int[] triangles = new int[topTriangles.Length * 2 + top.vertices.Count * 6]; for (int i = 0; i < topTriangles.Length; i += 3) { triangles[i] = topTriangles[i]; triangles[i + 1] = topTriangles[i + 1]; triangles[i + 2] = topTriangles[i + 2]; triangles[topTriangles.Length + i] = topTriangles[i + 2] + top.vertices.Count; triangles[topTriangles.Length + i + 1] = topTriangles[i + 1] + top.vertices.Count; triangles[topTriangles.Length + i + 2] = topTriangles[i] + top.vertices.Count; } // Find the triangles for the sides of the platform. for (int i = 0; i < top.vertices.Count; i++) { int triangleOffset = topTriangles.Length * 2 + i * 6; int nextIndex = i < top.vertices.Count - 1 ? i + 1 : 0; int vertexOffset = top.vertices.Count * 2 + i * 4; vertices[vertexOffset] = vertices[i]; vertices[vertexOffset + 1] = vertices[nextIndex]; vertices[vertexOffset + 2] = vertices[top.vertices.Count + i]; vertices[vertexOffset + 3] = vertices[top.vertices.Count + nextIndex]; if (!clockwise) { triangles[triangleOffset] = vertexOffset; triangles[triangleOffset + 1] = vertexOffset + 1; triangles[triangleOffset + 2] = vertexOffset + 2; triangles[triangleOffset + 3] = vertexOffset + 3; triangles[triangleOffset + 4] = vertexOffset + 2; triangles[triangleOffset + 5] = vertexOffset + 1; } else { triangles[triangleOffset + 5] = vertexOffset; triangles[triangleOffset + 4] = vertexOffset + 1; triangles[triangleOffset + 3] = vertexOffset + 2; triangles[triangleOffset + 2] = vertexOffset + 3; triangles[triangleOffset + 1] = vertexOffset + 2; triangles[triangleOffset] = vertexOffset + 1; } } mesh.vertices = vertices; mesh.triangles = triangles; mesh.RecalculateNormals(); virtualPlatform.AddComponent <MeshCollider>(); virtualPlatform.GetComponent <MeshCollider>().sharedMesh = mesh; virtualPlatform.transform.parent = LevelManager.Instance.transform.FindChild("Platforms").transform; return(virtualPlatform); }
void UpdateMesh() { positionWithOffset = new Vector3 (transform.position.x + 0.5f, 1.5f, transform.position.z + 0.5f); newVerts.Add (new Vector2( positionWithOffset.x, positionWithOffset.z ) ); for (int i =0; i < ConeResolution;i++) { var x = Mathf.Sin(angle); var y = Mathf.Cos(angle); angle += 2*Mathf.PI/ConeResolution; if( angle >= 360 ) angle = 0; Vector3 dir = new Vector3(x,0,y); float tempAngle = Vector3.Angle(dir, myUnit.facing); if( tempAngle < myUnit.fieldOfViewAngle* 0.5f ){ RaycastHit hit; if (Physics.Raycast (positionWithOffset, dir,out hit, distance)) { if( hit.transform.gameObject.tag == "FolkUnit" ){ Debug.DrawLine (positionWithOffset, hit.point, new Color(1,0,0,1)); } else { Debug.DrawLine (positionWithOffset, hit.point, new Color(1,1,0,1)); } Vector3 tmp = hit.point; newVerts.Add (new Vector2 ((int) tmp.x,(int) tmp.z ) ); //var tmp = lightmeshholder.transform.InverseTransformPoint(hit.point); //vertices[i] = Vector3(tmp.x,0.5,tmp.z); }else{ // no hit positionWithOffset.y = 0; Debug.DrawRay (positionWithOffset, dir*distance, new Color(1,1,0,1)); Vector3 tempVector = positionWithOffset + dir*distance; newVerts.Add (new Vector2( (int) tempVector.x, (int) tempVector.z) ); //var tmp2 = lightmeshholder.transform.InverseTransformPoint(lightmeshholder.transform.position+dir); //vertices[i] = Vector3(tmp2.x,0.5,tmp2.z); } } } Vector2[] vertArray = new Vector2[newVerts.Count]; int index = 0; foreach (Vector2 v in newVerts) { Debug.Log ( v.x + " " + v.y ); vertArray[index] = v; index++; } Triangulator tr = new Triangulator(vertArray); int[] indices = tr.Triangulate(); foreach (int i in indices) Debug.Log ("indices " + i); index = 0; Vector3[] vertArray3D = new Vector3[newVerts.Count]; foreach (Vector2 v in vertArray) { vertArray3D[index] = new Vector3(v.x, v.y, 0.1f); } newVerts.Clear (); Mesh myMesh = new Mesh(); myMesh.vertices = vertArray3D; myMesh.triangles = indices; myMesh.RecalculateNormals(); myMesh.RecalculateBounds(); // Set up game object with mesh; gameObject.AddComponent(typeof(MeshRenderer)); MeshFilter filter = gameObject.AddComponent(typeof(MeshFilter)) as MeshFilter; filter.mesh = myMesh; }
public void BuildMesh() { List <Vector3> _vertices = new List <Vector3>(); for (int i = 0; i < Corners.Count; i++) { int nextIndex, lastIndex; if (i > 0) { lastIndex = i - 1; } else { lastIndex = Corners.Count - 1; } if (i < Corners.Count - 1) { nextIndex = i + 1; } else { nextIndex = 0; } /*int segCount = Mathf.CeilToInt(( * Vector2.Distance((Corners[i].position + Corners[i].controlPoint1)/2, (Corners[i].controlPoint1 + Corners[nextIndex].controlPoint0) / 2) + * Vector2.Distance((Corners[nextIndex].position + Corners[nextIndex].controlPoint0) / 2, (Corners[i].controlPoint1 + Corners[nextIndex].controlPoint0) / 2) * ) * 50 * smootFactor);*/ int segCount = Mathf.CeilToInt(Mathf.Sqrt( Vector2.Distance(Corners[i].position, Corners[i].controlPoint1) + Vector2.Distance(Corners[nextIndex].controlPoint0, Corners[i].controlPoint1) + Vector2.Distance(Corners[nextIndex].controlPoint0, Corners[nextIndex].position) ) * smootFactor); if (Corners[i].isBezier && Corners[nextIndex].isBezier) { for (int j = 0; j < segCount; j++) { float t = (float)j / segCount; _vertices.Add(GetPointBezier(Corners[i].position, Corners[nextIndex].position, Corners[i].controlPoint1, Corners[nextIndex].controlPoint0, t)); } } else { _vertices.Add(Corners[i].position); } } Vector2[] vertices2D = new Vector2[_vertices.Count]; Vector3[] vertices = new Vector3[_vertices.Count]; for (int i = 0; i < _vertices.Count; i++) { vertices2D[i] = _vertices[i]; vertices[i] = _vertices[i]; } Triangulator tr = new Triangulator(vertices2D); int[] indices = tr.Triangulate(); Mesh msh = new Mesh(); msh.vertices = vertices; msh.triangles = indices; msh.uv = vertices2D; msh.RecalculateNormals(); msh.RecalculateBounds(); GetComponent <MeshFilter>().mesh = msh; area = Mathf.Abs(tr.Area()); if (GetComponent <PolygonCollider2D>()) { GetComponent <PolygonCollider2D>().points = vertices2D; } }
bool GenerateCollisionShapeFromEnemies() { if (GSB_SceneManager.Instance.SelectionMesh != null) { for (var i = 0; i < SelectingEnemies.Count; ++i) { _shapeVertices2D[i].x = SelectingEnemies[i].transform.position.x; _shapeVertices2D[i].y = SelectingEnemies[i].transform.position.y; } _triangulator.Init(_shapeVertices2D, SelectingEnemies.Count); int[] indices = _triangulator.Triangulate(); Mesh shapeMesh = null; var setTriangles = false; if (GSB_SceneManager.Instance.SelectionMesh.sharedMesh == null) { setTriangles = true; shapeMesh = new Mesh(); GSB_SceneManager.Instance.SelectionMesh.sharedMesh = shapeMesh; } else { shapeMesh = GSB_SceneManager.Instance.SelectionMesh.sharedMesh; } if (_shapeVertices3D == null || SelectingEnemies.Count > _shapeVertices3D.Length) { _shapeVertices3D = new Vector3[SelectingEnemies.Count]; } for (int i = 0; i < SelectingEnemies.Count; i++) { _shapeVertices3D[i].x = _shapeVertices2D[i].x; _shapeVertices3D[i].y = _shapeVertices2D[i].y; _shapeVertices3D[i].z = -0.15f; } if (shapeMesh != null) { shapeMesh.vertices = _shapeVertices3D; if (setTriangles) { shapeMesh.triangles = indices; } shapeMesh.RecalculateBounds(); } if (indices.Length == 3 && SelectingEnemies.Count == 4) { return(false); } return(true); } return(false); }
/// <summary> /// Prepares the vertices and triangulates the faces ready for creating a mesh. /// </summary> public override void PrepareForImport() { // Do we draw this face? if (FlagsHidden) { return; } if (Parent is InterRecord) { InterRecord ir = Parent as InterRecord; // Find vertex list VertexList vl = Children.Find(o => o is VertexList) as VertexList; if (vl != null) { int startIndex = ir.Vertices.Count; int[] triangles = null; ////////////////////////// // Triangle ////////////////////////// if (vl.Offsets.Count == 3) { // DuckbearLab: FIX! Inverted X so inverted order too triangles = new int[] { startIndex + 2, startIndex + 1, startIndex }; // Extract verts for this triangle foreach (int vwcI in vl.Offsets) { VertexWithColor vwc = Header.VertexPalette.Vertices[vwcI]; ir.Vertices.Add(vwc); } } ////////////////////////// // Polygon ////////////////////////// else { // Extract verts and positions for triangulation of this face List <Vector3> positions = new List <Vector3>(vl.Offsets.Count); Vector3 faceNormal = Vector3.zero; // Need the normal to convert the positions to 2d for triangulation. foreach (int vwcI in vl.Offsets) { VertexWithColor vwc = Header.VertexPalette.Vertices[vwcI]; ir.Vertices.Add(vwc); positions.Add(new Vector3((float)vwc.Coordinate[0], (float)vwc.Coordinate[1], (float)vwc.Coordinate[2])); if (vwc is VertexWithColorNormal) { faceNormal += (vwc as VertexWithColorNormal).Normal; } } faceNormal.Normalize(); // Triangulate the face Triangulator triangulator = new Triangulator(); triangulator.initTriangulator(positions, faceNormal); triangles = triangulator.Triangulate(0); // Apply index offset for (int i = 0; i < triangles.Length; ++i) { triangles[i] += startIndex; } } // We now have our triangles. Lets find the correct submesh to add them to. KeyValuePair <IntermediateMaterial, List <int> > submesh = ir.FindOrCreateSubMesh(this); submesh.Value.AddRange(triangles); } else { Log.WriteWarning(ID + "- Could not find vertex list for face"); } } else { Log.WriteWarning("Face is not a child of a InterRecord, can not create face."); } base.ImportIntoScene(); }
public override IEnumerator Build(Way w, MapChunkLoader mcl) { Vector3[] nodes = new Vector3[w.nodes.Count]; Vector2[] xz = new Vector2[w.nodes.Count]; float height = 0; mcl.mapManager.mapHash.Add(w.id); mcl.wayList.Add(w.id); GameObject roof = new GameObject(); // roof.transform.position = new Vector3(0, centroid.y, 0); roof.name = "Area - " + (2 * w.id).ToString(); mcl.mapManager.mapHash.Add(2 * w.id); mcl.wayList.Add(2 * w.id); roof.isStatic = true; if (w.name != null) { GameObject label = new GameObject(); FloatingLabel lb = label.AddComponent<FloatingLabel>(); lb.text = w.name; //lb.transform.position = centroid; lb.target = GameObject.FindGameObjectWithTag("Player").transform; label.transform.parent = roof.transform; } roof.transform.parent = mcl.transform; Mesh roofm = new Mesh(); roof.AddComponent<MeshRenderer>(); MeshFilter filter2 = roof.AddComponent<MeshFilter>(); roof.AddComponent<MeshCollider>(); string areaPath = Application.persistentDataPath + "Assets/Resources/Objs/" + roof.name + ".obj"; if (!File.Exists(areaPath)) // If the file isn't cached we calculate everything and then we cache it { if (w.height != 0) height = w.height; Vector3 centroid = new Vector3(); for (int a = 0; a < w.nodes.Count; a++) { yield return null; RaycastHit hit; Node n = w.nodes[a]; nodes[a] = new Vector3((float)((n.easthing - mcl.offsetPositionX) / MapChunkLoader.precision), 5000, (float)((n.northing - mcl.offsetPositionZ) / MapChunkLoader.precision)); if (Physics.Raycast(nodes[a], -Vector3.up, out hit, Mathf.Infinity, mcl.layerMask)) { nodes[a].y = hit.point.y + height + 0.5f; } else { nodes[a].y = 1; } xz[a] = new Vector2((float)((n.easthing - mcl.offsetPositionX) / MapChunkLoader.precision), (float)((n.northing - mcl.offsetPositionZ) / MapChunkLoader.precision)); centroid += nodes[a]; } centroid /= w.nodes.Count; centroid.y += 1; // Vector3 position = new Vector3(centroid.x, 5000, centroid.z); float baseHeight = 0; /*RaycastHit hit; if (Physics.Raycast(position, -Vector3.up, out hit, Mathf.Infinity, layerMask)) { baseHeight = hit.point.y; }*/ //centroid = new Vector3(centroid.x, centroid.y + baseHeight, centroid.z); Vector2[] xzRoof = new Vector2[w.nodes.Count - 1]; for (int a = 0; a < xzRoof.Length; a++) { xzRoof[a] = xz[a]; } Triangulator tr = new Triangulator(xzRoof); int[] indices = tr.Triangulate(); // Create the mesh roofm.vertices = nodes; roofm.triangles = indices; Vector2[] uvs = new Vector2[nodes.Length]; for (int a = 0; a < nodes.Length; a++) { if (a < nodes.Length - 1) { uvs[a] = new Vector2(Mathf.Abs(nodes[a].x) / nodes[nodes.Length - 1].x, Mathf.Abs(nodes[a].z) / nodes[nodes.Length - 1].x); } else { uvs[a] = new Vector2(1, 1); } } roofm.uv = uvs; roofm.RecalculateNormals(); roofm.RecalculateBounds(); filter2.sharedMesh = roofm; if (mcl.exportObjs) { ObjExporter oe = new ObjExporter(); oe.MeshToFile(filter2, areaPath); } } else { ObjImporter oi = new ObjImporter(); mcl.StartCoroutine(oi.FileToMesh("file://" + areaPath)); while (oi._myMesh == null) { yield return null; } filter2.sharedMesh = oi._myMesh; Debug.LogWarning("Loaded Area from cache " + areaPath); } if (w.type == WayType.Parking) roof.GetComponent<MeshRenderer>().material = Resources.Load("Materials/Parking Material") as Material; if (w.type == WayType.Park) roof.GetComponent<MeshRenderer>().material = Resources.Load("Materials/Park Material") as Material; if (w.type == WayType.RiverBank) roof.GetComponent<MeshRenderer>().material = Resources.Load("Materials/River Material") as Material; }
public override void Render(SVGElement parent, Material baseMaterial, onRenderCallback cb) { if (_gameobject == null) { _gameobject = new GameObject(name); _gameobject.AddComponent(typeof(MeshRenderer)); if (parent != null) { _gameobject.transform.parent = parent.gameObject.transform; } } if (vectors_2d != null && vectors_2d.Length > 0) { SVGGenerals.OptimizePoints(ref vectors_2d); // Use the triangulator to get indices for creating triangles Triangulator tr = new Triangulator(vectors_2d); int[] indices = tr.Triangulate(); // Create the Vector3 vertices Vector3[] vertices = new Vector3[vectors_2d.Length]; for (int i = 0; i < vertices.Length; i++) { vertices[i] = new Vector3(vectors_2d[i].x, vectors_2d[i].y, 0); } // Create the mesh if (msh == null) { msh = new Mesh(); } msh.vertices = vertices; msh.triangles = indices; if (fillColor != null) { // Use vertex colors Color[] colors = new Color[vertices.Length]; for (int i = 0; i < colors.Length; i++) { colors[i] = new Color(fillColor.R, fillColor.G, fillColor.B, fillOpacity); } msh.colors = colors; } //Normals //Vector3[] normals = new Vector3[vectors_2d.Length]; //for (int i = 0; i < normals.Length; i++) { // normals[i] = new Vector3(0, 0, 1); //} msh.RecalculateNormals(); msh.RecalculateBounds(); msh.RecalculateTangents(); //Generate Path mesh if (stroke != null) { stroke.GenerateMesh(vertices); Mesh strokeMesh = stroke.GetMesh(); CombineInstance combine = new CombineInstance(); combine.mesh = strokeMesh; combine.transform = _gameobject.transform.localToWorldMatrix; msh.CombineMeshes(new CombineInstance[] { combine }); } if (filter == null) { filter = gameObject.GetComponent <MeshFilter>(); } if (filter == null) { filter = gameObject.AddComponent(typeof(MeshFilter)) as MeshFilter; } filter.sharedMesh = msh; if (renderer == null) { renderer = gameObject.GetComponent <Renderer>(); } renderer.sharedMaterial = baseMaterial; //renderer.material = baseMaterial; //renderer.material.name = name + "-material"; //renderer.sortingLayerName = "USVG"; renderer.sortingOrder = element_number; //renderer.material.color = new Color(UnityEngine.Random.value, UnityEngine.Random.value, UnityEngine.Random.value); //if (fillColor != null){ // renderer.material.color = new Color(fillColor.R, fillColor.G, fillColor.B, fillOpacity); // renderer.material.renderQueue = 3000 + element_number; //} if (cb != null) { cb.Invoke(this.name + "_msh", msh); //cb.Invoke(renderer.material.name, renderer.material); } } }
public static void create(string name, List <Vector2> verticesList, float height, float zOffset, Material topMaterial, Material sideMaterial) { GameObject obstacle = new GameObject(name, typeof(MeshFilter), typeof(MeshRenderer)); MeshFilter mesh_filter = obstacle.GetComponent <MeshFilter> (); //Shadows currently disabled for TopMaterial -> switch on by ShadowCastingMode.On obstacle.GetComponent <Renderer>().shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; obstacle.GetComponent <Renderer>().material = topMaterial; Vector2[] vertices2D = verticesList.ToArray(); // Use the triangulator to get indices for creating triangles Triangulator tr = new Triangulator(vertices2D); int[] indicesArray = tr.Triangulate(); List <int> indices = new List <int>(); for (int i = 0; i < indicesArray.Length; i++) { indices.Add(indicesArray[i]); } // Create the Vector3 vertices List <Vector3> vertices = new List <Vector3>(); for (int i = 0; i < vertices2D.Length; i++) { vertices.Add(new Vector3(vertices2D[i].x, zOffset + height, vertices2D[i].y)); } // Create the mesh Mesh mesh = new Mesh(); GameObject walls = new GameObject(name + "_side", typeof(MeshFilter), typeof(MeshRenderer)); MeshFilter mesh_filter_walls = walls.GetComponent <MeshFilter> (); walls.GetComponent <Renderer>().material = sideMaterial; List <Vector2> uvs_walls = new List <Vector2>(); List <Vector3> vertices_walls = new List <Vector3>(); List <int> indices_walls = new List <int>(); foreach (Vector3 v in vertices) { vertices_walls.Add(new Vector3(v.x, zOffset, v.z)); vertices_walls.Add(new Vector3(v.x, zOffset, v.z)); vertices_walls.Add(new Vector3(v.x, height + zOffset, v.z)); vertices_walls.Add(new Vector3(v.x, height + zOffset, v.z)); } for (int i = 1; i <= vertices_walls.Count; i = i + 4) { indices_walls.Add(i); indices_walls.Add((i + 3) % vertices_walls.Count); indices_walls.Add(i + 2); indices_walls.Add(i + 2); indices_walls.Add((i + 3) % vertices_walls.Count); indices_walls.Add((i + 5) % vertices_walls.Count); } //double sided walls int indices_walls_count = indices_walls.Count; for (int i = indices_walls_count - 1; i >= 0; i--) { indices_walls.Add(indices_walls[i]); } for (int i = 0; i < vertices_walls.Count; i++) { float uv_height = height; int a = i - 3; if (a < 0) { a = a + vertices_walls.Count; } float uv_width = Vector3.Distance(vertices_walls[i], vertices_walls[a]); if ((i - 1) % 4 == 0) { uvs_walls.Add(new Vector2(0, 0)); } else if ((i - 3) % 4 == 0) { uvs_walls.Add(new Vector2(0, uv_height)); } else if (i % 4 == 0) { uvs_walls.Add(new Vector2(uv_width, 0)); } else { uvs_walls.Add(new Vector2(uv_width, uv_height)); } } Mesh mesh_walls = new Mesh(); mesh_walls.vertices = vertices_walls.ToArray(); mesh_walls.uv = uvs_walls.ToArray(); mesh_walls.triangles = indices_walls.ToArray(); mesh_walls.RecalculateNormals(); mesh_walls.RecalculateBounds(); mesh_walls = TangentHelper.TangentSolver(mesh_walls); mesh_filter_walls.mesh = mesh_walls; mesh.vertices = vertices.ToArray(); mesh.uv = verticesList.ToArray(); mesh.triangles = indices.ToArray(); mesh.RecalculateNormals(); mesh.RecalculateBounds(); //flip if needed if (mesh.normals [0].y == -1) { indices.Reverse(); mesh.triangles = indices.ToArray(); mesh.RecalculateNormals(); } mesh = TangentHelper.TangentSolver(mesh); mesh_filter.mesh = mesh; }
//stuff //private Color tempColor; // Start is called before the first frame update void Start() { //Calculate the angle per spoke so that the raycasts make a full rotation. raycastAngle = 360 / (amountOfRaycastSpokes + 1); //Initialize the array for the mesh creation. hitList = new Vector2[amountOfRaycastSpokes + 1]; //Set the circle collider radius to the control radius to potentially do a thing if (allowOverlapBetweenControlAreas) { gameObject.GetComponent <CircleCollider2D>().radius = controlRadius * 1.5f; } else { gameObject.GetComponent <CircleCollider2D>().radius = controlRadius * 1.5f; } //Set the startup hitDistanceList //for (int index = 0; index <= amountOfRaycastSpokes; index++){ //hitDistanceList.Add(controlRadius); //} //Create the control area mesh? //controlMesh = new Mesh(); //controlMesh.vertices = new Vector3[] {new Vector3(0, 0, 0), new Vector3(0, 1, 0), new Vector3(1, 1, 0)}; //controlMesh.uv = new Vector2[] {new Vector2(0, 0), new Vector2(0, 1), new Vector2(1, 1)}; //controlMesh.triangles = new int[] {0, 1, 2}; //Set the material of the mesh based on the player so it matches the material of the units if (gameObject.transform.parent.tag == "Player1Owned") { gameObject.GetComponent <MeshRenderer>().material = p1Material; //gameObject.GetComponent<MeshRenderer>().material.SetTexture("_MainTex", p1Texture); //gameObject.GetComponent<MeshRenderer>().material.SetTexture("_BumpMap", p1Texture); //tempColor = gameObject.GetComponent<MeshRenderer>().material.color; //gameObject.GetComponent<MeshRenderer>().material.color = new Color (tempColor.r, tempColor.g, tempColor.b, 0); gameObject.layer = 14; } else { gameObject.GetComponent <MeshRenderer>().material = p2Material; //gameObject.GetComponent<MeshRenderer>().material.SetTexture("_MainTex", p2Texture); //gameObject.GetComponent<MeshRenderer>().material.SetTexture("_BumpMap", p2Texture); //tempColor = gameObject.GetComponent<MeshRenderer>().material.color; //gameObject.GetComponent<MeshRenderer>().material.color = new Color (tempColor.r, tempColor.g, tempColor.b, 0); gameObject.layer = 15; } //If object is static the mesh and area only have to be checked once. if (isStatic) { //Radiate spokes out from the center of the control unit. //Check if they don't go through anything within the control radius. //If they do write down the distance at which they collide, if not write down the radius. //This way the control area won't go through walls. for (int index = 0; index <= amountOfRaycastSpokes; index++) { //Get a location and the Raycast hit tmpLoc = new Vector2(gameObject.transform.position.x, gameObject.transform.position.y); vec2Angle = (Vector2)(Quaternion.Euler(0, 0, raycastAngle * index) * Vector2.right); vec2Angle.Normalize(); tmpHit = Physics2D.Raycast(tmpLoc, vec2Angle, controlRadius); //Check if the raycast hit anything. If it did get the distance. If not save controlradius. if (tmpHit.collider != null) { //hitList.Add(tmpHit.point); hitList[index] = vec2Angle * (Vector2.Distance(tmpHit.point, tmpLoc)) * 2; } else { //hitList.Add(tmpLoc+vec2Angle); hitList[index] = vec2Angle * controlRadius * 2; } } //Creating triangles for mesh using Triangulator //Created by runevision //Available at http://wiki.unity3d.com/index.php?title=Triangulator //Usage based on example on wiki. Triangulator tr = new Triangulator(hitList); int[] indices = tr.Triangulate(); Vector3[] vertices = new Vector3[hitList.Length]; for (int i = 0; i < vertices.Length; i++) { vertices[i] = new Vector3(hitList[i].x, hitList[i].y, 0); } //Create the new mesh Mesh msh = new Mesh(); msh.vertices = vertices; msh.triangles = indices; msh.RecalculateNormals(); msh.RecalculateBounds(); //Set the new mesh to be the gameobject mesh. GetComponent <MeshFilter>().mesh = msh; //Add polygon collider to area control PolygonCollider2D pc = gameObject.AddComponent(typeof(PolygonCollider2D)) as PolygonCollider2D; pc.points = hitList; //if (gameObject.transform.parent.tag == "Player1Owned"){ // gameObject.GetComponent<MeshRenderer>().material.SetTexture("_MainTex", p1Texture); // gameObject.GetComponent<MeshRenderer>().material.SetTexture("_BumpMap", p1Texture); //} //else{ // gameObject.GetComponent<MeshRenderer>().material.SetTexture("_MainTex", p2Texture); // gameObject.GetComponent<MeshRenderer>().material.SetTexture("_BumpMap", p2Texture); //} } }
public void GenerateTriangles(Mesh mesh, RageVertex[] fillVerts, RageVertex[] embossVerts, RageVertex[] outlineVerts, bool AAfill, bool AAemboss, bool AAoutline, bool multipleMaterials) { int[] tris = null; Vector2[] verts = new Vector2[0]; if (GetFill() != Fill.Landscape) { if (AAfill) { verts = new Vector2[fillVerts.Length / 2]; } else { verts = new Vector2[fillVerts.Length]; } for (int i = 0; i < verts.Length; i++) { verts[i] = new Vector2(fillVerts[i].position.x, fillVerts[i].position.y); } } tris = new int[GetOutlineTriangleCount(outlineVerts, AAoutline) * 3 + GetFillTriangleCount(fillVerts, AAfill) * 3 + GetEmbossTriangleCount(embossVerts, AAemboss) * 3]; int tIndex = 0; int vertsPerBand = 0; int bandCount = 0; switch (GetFill()) { case Fill.None: break; case Fill.Solid: case Fill.Gradient: Triangulator triangulator = new Triangulator(verts); int[] fillTris = triangulator.Triangulate(); for (int i = 0; i < fillTris.Length; i++) { tris[tIndex++] = fillTris[i]; } break; case Fill.Landscape: if (AAfill) { bandCount = 2; vertsPerBand = fillVerts.Length / 3; } else { bandCount = 1; vertsPerBand = fillVerts.Length / 2; } for (int v = 0; v < vertsPerBand-1; v++) { for (int b = 0; b < bandCount; b++) { tris[tIndex++] = v + b * vertsPerBand; tris[tIndex++] = v + (b + 1) * vertsPerBand; tris[tIndex++] = v + (b + 1) * vertsPerBand + 1; tris[tIndex++] = v + b * vertsPerBand; tris[tIndex++] = v + (b + 1) * vertsPerBand + 1; tris[tIndex++] = v + b * vertsPerBand + 1; } } break; } vertsPerBand = 0; bandCount = 0; // fill antialiasing triangles if (AAfill) { vertsPerBand = verts.Length-1; for (int v = 0; v <= vertsPerBand; v++) { for (int b = 0; b < 1; b++) { tris[tIndex++] = v + b * vertsPerBand; tris[tIndex++] = v + (b + 1) * vertsPerBand; tris[tIndex++] = v + (b + 1) * vertsPerBand + 1; tris[tIndex++] = v + b * vertsPerBand; tris[tIndex++] = v + (b + 1) * vertsPerBand + 1; tris[tIndex++] = v + b * vertsPerBand + 1; } } } if (AAemboss) { vertsPerBand = embossVerts.Length / 4; bandCount = 3; } else { vertsPerBand = embossVerts.Length / 2; bandCount = 1; } for (int v = 0; v < vertsPerBand-1; v++) { for (int b = 0; b < bandCount; b++) { if (v < vertsPerBand - 1) { tris[tIndex++] = v + b * vertsPerBand + fillVerts.Length; tris[tIndex++] = v + (b + 1) * vertsPerBand + 1 + fillVerts.Length; tris[tIndex++] = v + (b + 1) * vertsPerBand + fillVerts.Length; tris[tIndex++] = v + b * vertsPerBand + fillVerts.Length; tris[tIndex++] = v + b * vertsPerBand + 1 + fillVerts.Length; tris[tIndex++] = v + (b + 1) * vertsPerBand + 1 + fillVerts.Length; } } } if (AAoutline) { vertsPerBand = outlineVerts.Length / 4; bandCount = 3; } else { vertsPerBand = outlineVerts.Length / 2; bandCount = 1; } for (int v = 0; v < vertsPerBand-1; v++) { for (int b = 0; b < bandCount; b++) { tris[tIndex++] = v + b * vertsPerBand + embossVerts.Length + fillVerts.Length; tris[tIndex++] = v + (b + 1) * vertsPerBand + 1 + embossVerts.Length + fillVerts.Length; tris[tIndex++] = v + (b + 1) * vertsPerBand + embossVerts.Length + fillVerts.Length; tris[tIndex++] = v + b * vertsPerBand + embossVerts.Length + fillVerts.Length; tris[tIndex++] = v + b * vertsPerBand + 1 + embossVerts.Length + fillVerts.Length; tris[tIndex++] = v + (b + 1) * vertsPerBand + 1 + embossVerts.Length + fillVerts.Length; } } // Free outline AA caps if (GetOutline() == Outline.Free && AAoutline) { int vertsInBand = outlineVerts.Length / 4; tris[tIndex++] = 0 + embossVerts.Length + fillVerts.Length; tris[tIndex++] = vertsInBand * 2 + embossVerts.Length + fillVerts.Length; tris[tIndex++] = vertsInBand + embossVerts.Length + fillVerts.Length; tris[tIndex++] = 0 + embossVerts.Length + fillVerts.Length; tris[tIndex++] = vertsInBand * 3 + embossVerts.Length + fillVerts.Length; tris[tIndex++] = vertsInBand * 2 + embossVerts.Length + fillVerts.Length; tris[tIndex++] = vertsInBand * 1 - 1 + embossVerts.Length + fillVerts.Length; tris[tIndex++] = vertsInBand * 3 - 1 + embossVerts.Length + fillVerts.Length; tris[tIndex++] = vertsInBand * 2 - 1 + embossVerts.Length + fillVerts.Length; tris[tIndex++] = vertsInBand * 1 - 1 + embossVerts.Length + fillVerts.Length; tris[tIndex++] = vertsInBand * 4 - 1 + embossVerts.Length + fillVerts.Length; tris[tIndex++] = vertsInBand * 3 - 1 + embossVerts.Length + fillVerts.Length; } if (multipleMaterials) { int ii = 0; int[] outlineTriangles = new int[GetOutlineTriangleCount(outlineVerts, AAoutline) * 3]; int[] restOfTriangles = new int[tris.Length - GetOutlineTriangleCount(outlineVerts, AAoutline) * 3]; mesh.subMeshCount = 2; for (; ii < restOfTriangles.Length; ii++) { restOfTriangles[ii] = tris[ii]; } if (GetTexturing1() == UVMapping.Fill) { mesh.SetTriangles(restOfTriangles, 0); } if (GetTexturing2() == UVMapping.Fill) { mesh.SetTriangles(restOfTriangles, 1); } for (; ii < tris.Length; ii++) { outlineTriangles[ii - restOfTriangles.Length] = tris[ii]; } if (GetTexturing1() == UVMapping.Outline) { mesh.SetTriangles(outlineTriangles, 0); } if (GetTexturing2() == UVMapping.Outline) { mesh.SetTriangles(outlineTriangles, 1); } } else { if (inverseTriangleDrawOrder) { int len = tris.Length; int[] triangles2 = new int[tris.Length]; for (int i = 0; i < len; i+=3) { triangles2[len - i - 3] = tris[i]; triangles2[len - i - 3 + 1] = tris[i + 1]; triangles2[len - i - 3 + 2] = tris[i + 2]; } tris = triangles2; } mesh.triangles = tris; } }
void MESH_init() { // Create Vector2 vertices vertices2D = new List <Vector2> (); vertices2D.Add(new Vector2(0, 0)); vertices2D.Add(new Vector2(-FOV_length * .5f, FOV_width)); vertices2D.Add(new Vector2(0, FOV_width)); vertices2D.Add(new Vector2(FOV_length * .5f, FOV_width)); // Use the triangulator to get indices for creating triangles Triangulator tr = new Triangulator(vertices2D); trias = tr.Triangulate(); // Create the Vector3 vertices verts = new Vector3[vertices2D.Count]; for (int i = 0; i < verts.Length; i++) { verts [i] = new Vector3(vertices2D [i].x, 0, vertices2D [i].y); } // Create the mesh mesh = new Mesh(); mesh.vertices = verts; mesh.triangles = trias; mesh.uv = vertices2D.ToArray(); mesh.RecalculateNormals(); mesh.RecalculateBounds(); if (mat == null) { mat = new Material(Shader.Find("Transparent/Diffuse")); //mat.mainTexture = texture; Color c = Color.green; c = new Color(c.r, c.g, c.b, .2f); mat.color = c; //new Color(1,.5f,0,.5f); } meshRenderer = (MeshRenderer)gameObject.GetComponent(typeof(MeshRenderer)); if (meshRenderer == null) { meshRenderer = (MeshRenderer)gameObject.AddComponent(typeof(MeshRenderer)); } meshFilter = (MeshFilter)gameObject.GetComponent(typeof(MeshFilter)); if (meshFilter == null) { meshFilter = (MeshFilter)gameObject.AddComponent(typeof(MeshFilter)); } meshFilter.mesh = mesh; meshRenderer.material = mat; meshCollider = (MeshCollider)gameObject.GetComponent(typeof(MeshCollider)); if (meshCollider == null) { meshCollider = (MeshCollider)gameObject.AddComponent(typeof(MeshCollider)); } meshCollider.sharedMesh = mesh; meshCollider.isTrigger = true; }
private void GenerateMesh(Vector2[] vertices2D, Vector2[] uv, Vector2[] uv2, GameObject parent) { // Use the triangulator to get indices for creating triangles Triangulator tr = new Triangulator(vertices2D); int[] indices = tr.Triangulate(); // Create the Vector3 vertices Vector3[] vertices = new Vector3[vertices2D.Length]; for (int i=0; i<vertices.Length; i++) { vertices[i] = new Vector3(vertices2D[i].x, 0, vertices2D[i].y); } // Create the mesh Mesh msh = new Mesh(); msh.vertices = vertices; msh.uv = uv; msh.uv2 = uv2; msh.triangles = indices; msh.RecalculateNormals(); msh.RecalculateBounds(); msh.Optimize(); GameObject go = new GameObject("Mesh"); var filter = go.AddComponent<MeshFilter>(); var render = go.AddComponent<MeshRenderer>(); var collider = go.AddComponent<BoxCollider>(); filter.mesh = msh; render.material = new Material(Shader.Find("Diffuse")); go.transform.SetParent(parent.transform); go.transform.localPosition = Vector3.zero; go.transform.localScale = Vector3.one; collider.center = msh.bounds.center; collider.size = msh.bounds.size; }
/// <summary>Get the verts/ tris/ uv of this in 3D.</summary> public void GetExtrude(Text3D text, int vertIndex, int triIndex, int vertCount, int triCount, float scale, ref float left, ref float top) { // What's the curve accuracy? float accuracy = TextExtrude.CurveAccuracy; if (Characters == null) { return; } // Create a triangulator - it will "select" a letter one at a time: Triangulator triangulator = new Triangulator(text.Vertices, 0, 0); triangulator.Clockwise = TextExtrude.Inverse; for (int c = 0; c < Characters.Length; c++) { Glyph character = Characters[c]; if (character == null || character.Space) { continue; } if (character.Width == 0f) { character.RecalculateMeta(); } if (Kerning != null) { left += Kerning[c] * FontSize; } int frontIndex = vertIndex; // The set of first nodes - these essentially identify where contours start. 0 is always present if there is at least one contour. List <int> firstNodes = new List <int>(); // Compute the vertices: character.GetVertices(text.Vertices, text.Normals, accuracy, left, -top, scale, ref vertIndex, firstNodes); // Duplicate and offset: int count = vertIndex - frontIndex; if (count == 0) { // Ignore continue; } // Future note: // - VectorPath.HoleSort seems to sort letters like i too. // - This results in a count of 1 (we're expecting 2) // - For each contour (foreach firstNodes), triangulate individually. // - Ensure the triangle count matches too. May need to move firstNodes set. // Select these verts in the triangulator: triangulator.Select(frontIndex, count); // Dupe the verts: for (int v = 0; v < count; v++) { Vector3 vert = text.Vertices[frontIndex + v]; vert.z = Extrude; text.Vertices[vertIndex + v] = vert; text.Normals[vertIndex + v] = new Vector3(0f, 0f, 1f); text.Normals[frontIndex + v] = new Vector3(0f, 0f, -1f); } // How many tri's in this char? (single face only) int charTris = count - 2; // Perform triangulation of the front face: triangulator.Triangulate(text.Triangles, charTris, triIndex); // Seek: int triIndexCount = charTris * 3; triIndex += triIndexCount; // Duplicate the results for the back face and invert them: for (int t = 0; t < charTris; t++) { text.Triangles[triIndex] = count + text.Triangles[triIndex - triIndexCount]; triIndex++; // Last two are inverted as the back face looks the other way: text.Triangles[triIndex] = count + text.Triangles[triIndex - triIndexCount + 1]; triIndex++; text.Triangles[triIndex] = count + text.Triangles[triIndex - triIndexCount - 1]; triIndex++; } // Time for the sides! // How many contours? int contourCount = firstNodes.Count; // Get the current first: int currentFirst = firstNodes[0]; int contourIndex = 1; // Get the "next" first: int nextFirst; if (contourCount > 1) { nextFirst = firstNodes[1]; } else { nextFirst = -1; } // Get the back face vertex indices: int backIndex = vertIndex; // For each edge.. for (int i = 0; i < count; i++) { // Get the next index: int next = i + 1; if (next == count || next == nextFirst) { // Loop back instead: next = currentFirst; // Advance to the next one: currentFirst = nextFirst; contourIndex++; // Update nextFirst too: if (contourIndex < contourCount) { nextFirst = firstNodes[contourIndex]; } else { nextFirst = -1; } } // Add two triangles from front face -> back face: text.Triangles[triIndex] = frontIndex + i; triIndex++; text.Triangles[triIndex] = backIndex + i; triIndex++; text.Triangles[triIndex] = backIndex + next; triIndex++; text.Triangles[triIndex] = frontIndex + next; triIndex++; text.Triangles[triIndex] = frontIndex + i; triIndex++; text.Triangles[triIndex] = backIndex + next; triIndex++; } // Seek vert index over the backface: vertIndex += count; // Move left along: left += (character.AdvanceWidth * FontSize) + LetterSpacing; } }
bool ConvertCountries() { List<CNode> foundNodes = new List<CNode> (); ConnectedNodes (nodes [0], foundNodes); if (foundNodes.Count == nodes.Count && nodes.FindAll (x => x.links.Count < 2).Count == 0) { //Debug.Log ("All nodes are connected by two links"); List<List<CNode>> nodeShapes = new List<List<CNode>> (); List<CNode> multiNodes = nodes.FindAll (x => x.links.Count > 2); /*if(multiNodes.Count == 0) { nodeShapes.Add(nodes); }*/ List<CNode[]> doneNodes = new List<CNode[]> (); foreach (CNode junction in multiNodes) { //we loop through each junction to catch all the shapes List<CNode> cwNodes = junction.CClockwiseConnected (); foreach (CNode node in cwNodes) { //we go around each node, looking for its clockwise next point if (doneNodes.Find (x => x [0] == node && x [1] == junction) != null) { continue; } float angleSum = 0f; doneNodes.Add (new CNode[2]{node, junction}); //we start by adding the node so we don't go around it clockwise again CNode currentNode = junction; CNode lastNode = node; //Debug.Log ("Started from " + lastNode.gameObject.name + " and " + currentNode.gameObject.name); List<CNode> currentShape = new List<CNode> (); currentShape.Add (node); do { CNode temp = currentNode; currentShape.Add (currentNode); currentNode = currentNode.CClockwiseFrom (lastNode); float addAngle = MeshMaker.GetCWAngle(temp.gameObject.transform.position, lastNode.gameObject.transform.position, currentNode.gameObject.transform.position) - Mathf.PI; //we look at the exterior angle, which is why we subtract Pi //Debug.Log ("Angle between " + lastNode.gameObject.name + " and " + currentNode.gameObject.name + " is " + addAngle.ToString()); angleSum += addAngle; lastNode = temp; //Debug.Log ("Added " + currentNode.gameObject.name); if (currentNode.links.Count > 2) { //if it's a node before a junction, we might loop through it in the future and want to avoid it now doneNodes.Add (new CNode[2]{lastNode, currentNode}); } } while(currentNode != node); //Debug.Log (angleSum.ToString()); if(angleSum < 0) { //This is true for shapes we've gone around the inside of - otherwise, we can include a negative shape nodeShapes.Add (currentShape); } } } for (int nodeIndex = 0; nodeIndex < nodeShapes.Count; nodeIndex++) { //we generate the shapes out of the list of CNodes List<CNode> nodeList = nodeShapes [nodeIndex]; Vector3[] vertices = new Vector3[nodeList.Count]; Vector3 averageVert = new Vector3(); for (int i = 0; i < nodeList.Count; i++) { averageVert += nodeList [i].gameObject.transform.position; } averageVert /= nodeList.Count; for (int i = 0; i < nodeList.Count; i++) { vertices[i] = nodeList [i].gameObject.transform.position - averageVert; } Triangulator triangulator = new Triangulator (vertices); triangulator.Triangulate (); GameObject newObject = new GameObject (); MeshFilter newFilter = newObject.AddComponent<MeshFilter> (); newFilter.mesh.vertices = vertices; newFilter.mesh.triangles = triangulator.Triangulate (); newFilter.mesh.RecalculateBounds (); newFilter.mesh.RecalculateNormals (); MeshRenderer newRenderer = newObject.AddComponent<MeshRenderer> (); newRenderer.material.shader = Shader.Find ("UI/Default"); float colorFraction = nodeIndex / (nodeShapes.Count * 1.0f); //Debug.Log ("Coloring at " + colorFraction.ToString ()); newRenderer.material.color = new Color (colorFraction, colorFraction, colorFraction, 1f); newObject.AddComponent<MeshCollider>(); newObject.AddComponent<CountryObject>(); newObject.transform.Translate(averageVert + new Vector3(0f, 0f, 1f)); MeshMaker.GenerateOutline(newObject); } return true; } return false; }
/// <summary> /// Updates the mesh according to the Voronoi DCEL. /// </summary> private void UpdateMesh() { if (m_meshFilter.mesh == null) { // create initial mesh m_meshFilter.mesh = new Mesh { subMeshCount = 2 }; m_meshFilter.mesh.MarkDynamic(); } else { // clear old mesh m_meshFilter.mesh.Clear(); m_meshFilter.mesh.subMeshCount = 2; } // build vertices and triangle list var vertices = new List <Vector3>(); var triangles = new List <int>[2] { new List <int>(), new List <int>() }; // iterate over vertices and create triangles accordingly foreach (var inputNode in m_delaunay.Vertices) { // dont draw anything for unowned vertices if (m_ownership[inputNode] == EOwnership.UNOWNED) { continue; } // get ownership of node var playerIndex = m_ownership[inputNode] == EOwnership.PLAYER1 ? 0 : 1; var face = m_DCEL.GetContainingFace(inputNode); // cant triangulate outer face if (face.IsOuter) { continue; } // triangulate face polygon var triangulation = Triangulator.Triangulate(face.Polygon.Outside); // add triangles to correct list foreach (var triangle in triangulation.Triangles) { int curCount = vertices.Count; // add triangle vertices vertices.Add(new Vector3(triangle.P0.x, 0, triangle.P0.y)); vertices.Add(new Vector3(triangle.P1.x, 0, triangle.P1.y)); vertices.Add(new Vector3(triangle.P2.x, 0, triangle.P2.y)); // add triangle to mesh according to owner triangles[playerIndex].Add(curCount); triangles[playerIndex].Add(curCount + 1); triangles[playerIndex].Add(curCount + 2); } } // update mesh m_meshFilter.mesh.vertices = vertices.ToArray(); m_meshFilter.mesh.SetTriangles(triangles[0], 0); m_meshFilter.mesh.SetTriangles(triangles[1], 1); m_meshFilter.mesh.RecalculateBounds(); // set correct uv var newUVs = new List <Vector2>(); foreach (var vertex in vertices) { newUVs.Add(new Vector2(vertex.x, vertex.z)); } m_meshFilter.mesh.uv = newUVs.ToArray(); }
void Sonar() { mesh.Clear(); points.Clear(); angles.Clear(); for (int i = 0; i < planets.Length; i++) { points.Add(planets[i].GetComponent <PolygonCollider2D>().points); } for (int i = 0; i < points.Count; i++) { for (int j = 0; j < points[i].Length; j++) { Vector2 pppp = planets[i].transform.TransformPoint(points[i][j] * 1.1f); Vector2 norm = (pppp - (Vector2)transform.position).normalized; hit = Physics2D.Raycast((Vector2)this.transform.position, (pppp + norm * 5f) - (Vector2)transform.position, 5000.0f, 9); if (hit.point == new Vector2(0, 0)) { mesh.Add((pppp + norm * 2f) - (Vector2)transform.position); } else { mesh.Add(hit.point - (Vector2)transform.position); } } } Vector2 pos = Camera.main.ScreenToWorldPoint(new Vector2(0, 0)); hit = Physics2D.Raycast((Vector2)this.transform.position, pos - (Vector2)transform.position, 500.0f); if (hit.point == new Vector2(0, 0)) { mesh.Add(pos - (Vector2)transform.position); } pos = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, 0)); hit = Physics2D.Raycast((Vector2)this.transform.position, pos - (Vector2)transform.position, 500.0f); if (hit.point == new Vector2(0, 0)) { mesh.Add(pos - (Vector2)transform.position); } pos = Camera.main.ScreenToWorldPoint(new Vector2(0, Screen.height)); hit = Physics2D.Raycast((Vector2)this.transform.position, pos - (Vector2)transform.position, 500.0f); if (hit.point == new Vector2(0, 0)) { mesh.Add(pos - (Vector2)transform.position); } pos = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, Screen.height)); hit = Physics2D.Raycast((Vector2)this.transform.position, pos - (Vector2)transform.position, 500.0f); if (hit.point == new Vector2(0, 0)) { mesh.Add(pos - (Vector2)transform.position); } for (int i = 0; i < mesh.Count; i++) { for (int j = 0; j < (mesh.Count - 1); j++) { float ang = Vector2.Angle(transform.position, mesh[j]); float ang_2 = Vector2.Angle(transform.position, mesh[j + 1]); Vector3 cross = Vector3.Cross(transform.position, mesh[j]); if (cross.z > 0) { ang = 360 - ang; } cross = Vector3.Cross(transform.position, mesh[j + 1]); if (cross.z > 0) { ang_2 = 360 - ang_2; } if (ang > ang_2) { temp = mesh[j]; mesh[j] = mesh[j + 1]; mesh[j + 1] = temp; } } } for (int i = 0; i < mesh.Count; i++) { float ang = Vector2.Angle(transform.position, mesh[i]); Vector3 cross = Vector3.Cross(transform.position, mesh[i]); if (cross.z > 0) { ang = 360 - ang; } angles.Add(ang); } Vector2[] vec_mesh = new Vector2[mesh.Count]; for (int i = 0; i < mesh.Count; i++) { vec_mesh[i] = mesh[i]; } // Use the triangulator to get indices for creating triangles Triangulator tr = new Triangulator(vec_mesh); int[] indices = tr.Triangulate(); // Create the Vector3 vertices Vector3[] vertices = new Vector3[vec_mesh.Length]; for (int i = 0; i < vertices.Length; i++) { vertices[i] = new Vector3(vec_mesh[i].x, vec_mesh[i].y, 0); } // Create the mesh msh = new Mesh(); msh.vertices = vertices; msh.triangles = indices; msh.RecalculateNormals(); msh.RecalculateBounds(); // Set up game object with mesh; filter.mesh = msh; }
void Thing() { msh = new Mesh(); // Create Vector2 vertices Vector2[] vertices2D = new Vector2[GetComponent <BezierCollider2D>().pointsQuantity + 3]; for (int i = 0; i < GetComponent <BezierCollider2D>().pointsQuantity + 3; i++) { if (i == GetComponent <BezierCollider2D>().pointsQuantity + 1) { switch (direction) { case Direction.up: vertices2D[GetComponent <BezierCollider2D>().pointsQuantity + 1] = new Vector2(GetComponent <BezierCollider2D>().points[i - 1].x, GetComponent <BezierCollider2D>().points[i - 1].y + downAmountX); break; case Direction.down: vertices2D[GetComponent <BezierCollider2D>().pointsQuantity + 1] = new Vector2(GetComponent <BezierCollider2D>().points[i - 1].x, GetComponent <BezierCollider2D>().points[i - 1].y - downAmountX); break; case Direction.left: vertices2D[GetComponent <BezierCollider2D>().pointsQuantity + 1] = new Vector2(GetComponent <BezierCollider2D>().points[i - 1].x - downAmountX, GetComponent <BezierCollider2D>().points[i - 1].y); break; case Direction.right: vertices2D[GetComponent <BezierCollider2D>().pointsQuantity + 1] = new Vector2(GetComponent <BezierCollider2D>().points[i - 1].x + downAmountX, GetComponent <BezierCollider2D>().points[i - 1].y); break; } } else if (i == GetComponent <BezierCollider2D>().pointsQuantity + 2) { switch (direction) { case Direction.up: vertices2D[GetComponent <BezierCollider2D>().pointsQuantity + 2] = new Vector2(GetComponent <BezierCollider2D>().points[0].x, GetComponent <BezierCollider2D>().points[0].y + downAmountY); break; case Direction.down: vertices2D[GetComponent <BezierCollider2D>().pointsQuantity + 2] = new Vector2(GetComponent <BezierCollider2D>().points[0].x, GetComponent <BezierCollider2D>().points[0].y - downAmountY); break; case Direction.left: vertices2D[GetComponent <BezierCollider2D>().pointsQuantity + 2] = new Vector2(GetComponent <BezierCollider2D>().points[0].x - downAmountY, GetComponent <BezierCollider2D>().points[0].y); break; case Direction.right: vertices2D[GetComponent <BezierCollider2D>().pointsQuantity + 2] = new Vector2(GetComponent <BezierCollider2D>().points[0].x + downAmountY, GetComponent <BezierCollider2D>().points[0].y); break; } } else { vertices2D[i] = GetComponent <BezierCollider2D>().points[i]; } } // Use the triangulator to get indices for creating triangles Triangulator tr = new Triangulator(vertices2D); int[] indices = tr.Triangulate(); // Create the Vector3 vertices Vector3[] vertices = new Vector3[vertices2D.Length]; for (int i = 0; i < vertices.Length; i++) { vertices[i] = new Vector3(vertices2D[i].x, vertices2D[i].y, 0); } TestUvRoofMap(msh); // Create the mesh msh.vertices = vertices; msh.triangles = indices; msh.RecalculateNormals(); msh.RecalculateBounds(); // Set up game object with mesh; GetComponent <MeshRenderer>().material = mat; MeshFilter filter = gameObject.GetComponent <MeshFilter>(); filter.mesh = msh; }
// Use this for initialization void Start() { //making terrain mesh mf = GetComponent <MeshFilter> (); mesh = mf.mesh; //vertices of mesh int mid_vertices = 7; Vector2[] vertices2D = new Vector2[4 + mid_vertices + mid_vertices]; vertices2D [0] = new Vector2(-3f, 2); //0, start point of first slope vertices2D [mid_vertices + 1] = new Vector2(-1f, 5.5f); //1, end point of first slope vertices2D [mid_vertices + 2] = new Vector2(1f, 5.5f); //2, first point of second slope vertices2D [vertices2D.Length - 1] = new Vector2(3f, 2); //2, end point of second slope //mid vertices on first slope Vector2[] mid_vertices_up = Mid_Bisection_Rec(vertices2D [0], vertices2D [mid_vertices + 1]); for (int i = 0; i < mid_vertices_up.Length; i++) { vertices2D [i + 1] = mid_vertices_up [i]; } //mid vertices on second slope Vector2[] mid_vertices_down = Mid_Bisection_Rec(vertices2D [mid_vertices + 2], vertices2D [vertices2D.Length - 1]); for (int i = 0; i < mid_vertices_down.Length; i++) { vertices2D [i + mid_vertices + 3] = mid_vertices_down [i]; } //vertices [1] = Mid_Bisection (vertices [0],vertices [vertices.Length-2]); //triangulate Triangulator tr = new Triangulator(vertices2D); int[] indices = tr.Triangulate(); //UV Vector2[] uvs = new Vector2[vertices2D.Length]; for (int i = 0; i < vertices2D.Length; i++) { uvs[i] = vertices2D[i]; } //convert 2d Vertices to 3d Vector3[] vertices3d = new Vector3[vertices2D.Length]; for (int i = 0; i < vertices2D.Length; i++) { vertices3d[i] = new Vector3(vertices2D[i].x, vertices2D[i].y, 0); } //map to mesh mesh.Clear(); mesh.vertices = vertices3d; mesh.triangles = indices; mesh.uv = uvs; mesh.RecalculateNormals(); //add mesh collider // MeshCollider msh_col = gameObject.AddComponent<MeshCollider>(); // msh_col.sharedMesh = mesh; // msh_col.convex = true; PolygonCollider2D pol_col = gameObject.AddComponent <PolygonCollider2D>(); pol_col.points = vertices2D; }
public void CreatePolygonMesh() { if (polygonCollider != null) { // Unparent the skin temporarily before adding the mesh Transform polygonParent = polygonCollider.transform.parent; polygonCollider.transform.parent = null; // Reset the rotation before creating the mesh so the UV's will align properly Quaternion localRotation = polygonCollider.transform.localRotation; polygonCollider.transform.localRotation = Quaternion.identity; // Reset the scale before creating the mesh so the UV's will align properly Vector3 localScale = polygonCollider.transform.localScale; polygonCollider.transform.localScale = Vector3.one; Vector2[] vertices2D = polygonCollider.points; // Use the triangulator to get indices for creating triangles int[] indices = Triangulator.Triangulate(vertices2D); // Create the Vector3 vertices Vector3[] vertices = new Vector3[vertices2D.Length]; for (int i = 0; i < vertices.Length; i++) { vertices[i] = new Vector3(vertices2D[i].x, vertices2D[i].y, 0); } // Create the mesh Mesh mesh = new Mesh(); mesh.vertices = vertices; mesh.triangles = indices; spriteRenderer = polygonCollider.GetComponent <SpriteRenderer>(); if (spriteRenderer != null) { mesh.uv = genUV(mesh.vertices); mesh.RecalculateNormals(); mesh.RecalculateBounds(); } else { Vector2[] uvs = new Vector2[vertices.Length]; Bounds bounds = polygonCollider.bounds; int n = 0; while (n < uvs.Length) { uvs[n] = new Vector2(vertices[n].x / bounds.size.x, vertices[n].y / bounds.size.x); n++; } mesh.uv = uvs; mesh.RecalculateNormals(); mesh.RecalculateBounds(); } ScriptableObjectUtility.CreateAsset(mesh); // Reset the rotations of the object polygonCollider.transform.localRotation = localRotation; polygonCollider.transform.localScale = localScale; polygonCollider.transform.parent = polygonParent; } }
private void UpdateMesh(Polygon2D Hull, int playerIndex, bool canMerge) { // build vertices and triangle list var vertices = new List <Vector3>(); var triangles = new List <int> (); Triangulation triangulation = Triangulator.Triangulate(Hull); // add triangles to correct list foreach (var triangle in triangulation.Triangles) { int curCount = vertices.Count; // add triangle vertices vertices.Add(new Vector3(triangle.P0.x, triangle.P0.y)); vertices.Add(new Vector3(triangle.P1.x, triangle.P1.y)); vertices.Add(new Vector3(triangle.P2.x, triangle.P2.y)); // add triangle to mesh according to owner triangles.Add(curCount); triangles.Add(curCount + 1); triangles.Add(curCount + 2); } // TODO: set correct uv ???? not sure if this is correct var newUVs = new List <Vector2>(); foreach (var vertex in vertices) { newUVs.Add(new Vector2(vertex.x, vertex.y)); } Mesh mesh = new Mesh(); // update mesh mesh.vertices = vertices.ToArray(); mesh.triangles = triangles.ToArray(); mesh.uv = newUVs.ToArray(); mesh.RecalculateBounds(); //create new object(new mesh filter) for this polygon var newPolygonInstance = Instantiate(PlayerPolygonMeshPrefab[playerIndex], Vector3.forward, Quaternion.identity) as GameObject; newPolygonInstance.transform.parent = PlayerPolygonMeshCollection[playerIndex].transform; newPolygonInstance.GetComponent <MeshFilter>().mesh = mesh; newPolygonInstance.GetComponent <MeshCollider>().sharedMesh = mesh; newPolygonInstance.GetComponent <P2Hull>().hull = Hull; newPolygonInstance.GetComponent <P2Hull>().mergeChance = canMerge; newPolygonInstance.GetComponent <P2Hull>().belongToPlayer1 = player1Turn; PlayerPolygonObjects[playerIndex].Add(newPolygonInstance); //TODO: add selected material (DONE IN P2HULL.cs) }
protected override void OnPopulateMesh(VertexHelper vh) { prevText = text; Vector2 totalSize = GetComponent <RectTransform>().rect.size; Vector2 topLeft = GetComponent <RectTransform>().rect.min; TextAnchor horzAlign = TextAnchor.UpperCenter; if (alignment == TextAnchor.MiddleCenter || alignment == TextAnchor.LowerCenter) { horzAlign = TextAnchor.UpperCenter; } if (alignment == TextAnchor.MiddleLeft || alignment == TextAnchor.LowerLeft || alignment == TextAnchor.UpperLeft) { horzAlign = TextAnchor.UpperLeft; } if (alignment == TextAnchor.MiddleRight || alignment == TextAnchor.LowerRight || alignment == TextAnchor.UpperRight) { horzAlign = TextAnchor.UpperRight; } UIVertex [] tmpVert = new UIVertex[4]; float lineHeight = (float)fontSize * (float)font.lineHeight / (float)font.fontSize; float sizeFraction = (float)lineHeight / (GetComponent <RectTransform>().rect.size.y); CalculateSlices(sizeFraction); // the textgenerator allows us to layout text (and to find line lengths etc.) TextGenerator generator = new TextGenerator(); TextGenerationSettings settings = new TextGenerationSettings(); vh.Clear(); if (showPoly) { Triangulator tr = new Triangulator(clipPoly); int[] indices = tr.Triangulate(); // Create the UIVertex vertices UIVertex ver = UIVertex.simpleVert; for (int i = 0; i < clipPoly.Count; i++) { ver.position.x = topLeft.x + clipPoly[i].x * totalSize.x; ver.position.y = topLeft.y + (totalSize.y - clipPoly[i].y * totalSize.y); ver.position.z = 0; // ver.position.y-=drawRect.y*totalSize.y; // ver.position.x+=thisWidth*.5f; // ver.position.x-=totalSize.x*.5f; // ver.position.x+=drawRect.x*totalSize.x; vh.AddVert(ver); } for (int i = 0; i < indices.Length; i += 3) { vh.AddTriangle(indices[i], indices[i + 1], indices[i + 2]); } return; } settings.textAnchor = horzAlign; settings.color = color; settings.pivot = new Vector2(0.5f, 0.5f); settings.richText = true; settings.font = font; settings.fontSize = fontSize; settings.fontStyle = FontStyle.Normal; settings.verticalOverflow = VerticalWrapMode.Overflow; settings.horizontalOverflow = HorizontalWrapMode.Wrap; settings.lineSpacing = 1; settings.scaleFactor = 1f; settings.generateOutOfBounds = false; List <string> sliceLines = new List <string>(); List <Rect> slicePositions = new List <Rect>(); // if (alignment == TextAnchor.UpperCenter || alignment == TextAnchor.UpperRight || alignment == TextAnchor.UpperLeft) { // top down - wrap normally and put each line into a slice in turn // n.b. if first word is longer than the first slice then try to change start slice until it does fit in // if that fails completely then retry from start ignoring that split bool dontSplitFirstWord = true; for (int z = 0; z < 2; z++) { for (int startSlice = 0; startSlice < slices.Count; startSlice++) { sliceLines.Clear(); slicePositions.Clear(); string textLeft = text; bool firstLine = true; for (int c = startSlice; c < slices.Count; c++) { float thisWidth = slices[c].width * totalSize.x; //print(slices[c].y); Rect r = slices[c]; settings.generationExtents = new Vector2(thisWidth, totalSize.y); generator.Populate(textLeft, settings); float maxVertex = generator.verts.Count; slicePositions.Add(slices[c]); if (generator.lines.Count > 1) { if (firstLine) { firstLine = false; print(generator.lines.Count + "!" + generator.lines[1].startCharIdx + "!"); // check that a word hasn't been split on the first line //print("***"+textLeft[generator.lines[1].startCharIdx-1]+"***"); if (char.IsLetterOrDigit(textLeft[generator.lines[1].startCharIdx - 1]) && dontSplitFirstWord) { print("Letter or digit at end, dropping out"); // drop out and try the next start slice break; } } sliceLines.Add(textLeft.Substring(0, generator.lines[1].startCharIdx)); // maxVertex=generator.lines[1].startCharIdx*4; textLeft = textLeft.Substring(generator.lines[1].startCharIdx); } else { sliceLines.Add(textLeft); textLeft = ""; break; } } if (textLeft.Length == 0) { break; } } dontSplitFirstWord = false; } } else if (alignment == TextAnchor.LowerCenter || alignment == TextAnchor.LowerRight || alignment == TextAnchor.LowerLeft) { // bottom up - hard case - try 1 slice, then 2 slices until whole text is used or whole slices are used.. for (int startSlice = slices.Count - 1; startSlice >= 0; startSlice--) { sliceLines.Clear(); slicePositions.Clear(); string textLeft = text; bool lastWrapWasSeparator = true; for (int c = startSlice; c < slices.Count; c++) { Rect r = slices[c]; float thisWidth = r.width * totalSize.x; //print(c+":"+thisWidth); settings.generationExtents = new Vector2(thisWidth, totalSize.y); generator.Populate(textLeft, settings); float maxVertex = generator.verts.Count; slicePositions.Add(r); if (generator.lines.Count > 1) { sliceLines.Add(textLeft.Substring(0, generator.lines[1].startCharIdx)); textLeft = textLeft.Substring(generator.lines[1].startCharIdx); } else { sliceLines.Add(textLeft); textLeft = ""; break; } } if (textLeft.Length == 0) { break; } } } else if (alignment == TextAnchor.MiddleCenter || alignment == TextAnchor.MiddleRight || alignment == TextAnchor.MiddleLeft) { // middle vertical alignment // try 1 line, 2 line and so on until we get one that fits the text // for (int numSlices = 1; numSlices <= slices.Count; numSlices++) { bool offset = (slices.Count & 1) != (numSlices & 1); int startSlice = offset?(offsetSlices.Count / 2) - numSlices / 2:(slices.Count / 2) - numSlices / 2; int endSlice = numSlices + startSlice; //print("try slices: "+numSlices+":"+offset+":"+startSlice); sliceLines.Clear(); slicePositions.Clear(); string textLeft = text; for (int c = startSlice; c < endSlice; c++) { Rect r = offset?offsetSlices[c]:slices[c]; float thisWidth = r.width * totalSize.x; settings.generationExtents = new Vector2(thisWidth, totalSize.y); generator.Populate(textLeft, settings); float maxVertex = generator.verts.Count; slicePositions.Add(r); if (generator.lines.Count > 1) { sliceLines.Add(textLeft.Substring(0, generator.lines[1].startCharIdx)); textLeft = textLeft.Substring(generator.lines[1].startCharIdx); } else { sliceLines.Add(textLeft); textLeft = ""; break; } } if (textLeft.Length == 0) { // filled up this one just right break; } } } for (int c = 0; c < sliceLines.Count; c++) { Rect drawRect = slicePositions[c]; float thisWidth = drawRect.width * totalSize.x; settings.textAnchor = horzAlign; settings.color = color; settings.generationExtents = new Vector2(thisWidth, totalSize.y); settings.pivot = new Vector2(0.5f, 0.5f); settings.richText = true; settings.font = font; settings.fontSize = fontSize; settings.fontStyle = FontStyle.Normal; settings.verticalOverflow = VerticalWrapMode.Overflow; settings.horizontalOverflow = HorizontalWrapMode.Wrap; settings.lineSpacing = 1; settings.scaleFactor = 1f; settings.generateOutOfBounds = false; generator.Populate(sliceLines[c], settings); for (int i = 0; i < generator.verts.Count; i += 4) { tmpVert[0] = generator.verts[i]; tmpVert[1] = generator.verts[i + 1]; tmpVert[2] = generator.verts[i + 2]; tmpVert[3] = generator.verts[i + 3]; for (int k = 0; k < 4; k += 1) { tmpVert[k].position.y -= drawRect.y * totalSize.y; tmpVert[k].position.x += thisWidth * .5f; tmpVert[k].position.x -= totalSize.x * .5f; tmpVert[k].position.x += drawRect.x * totalSize.x; } vh.AddUIVertexQuad(tmpVert); } } }
void Start() { // Create Vector2 vertices Vector2[] vertices2D = null; switch (tipo) { case Tipo.CAPSULE: vertices2D = USVG.PolygonTools.CreateCapsule(Height, Radius, Edges); break; case Tipo.CIRCLE: vertices2D = PolygonTools.CreateCircle(Radius, Edges); break; case Tipo.ELIPSE: vertices2D = PolygonTools.CreateEllipse(Radius, yRadius, Edges); break; case Tipo.GEAR: vertices2D = PolygonTools.CreateGear(Radius, NumberOfTheeth, TipPercentage, ToothHeight); break; case Tipo.ROUNDED_RECTANGLE: vertices2D = PolygonTools.CreateRoundedRectangle(Height, Width, Radius, yRadius, Edges); break; default: case Tipo.RECTANGLE: vertices2D = PolygonTools.CreateRectangle(Height, Width); break; } // Use the triangulator to get indices for creating triangles Triangulator tr = new Triangulator(vertices2D); int[] indices = tr.Triangulate(); // Create the Vector3 vertices Vector3[] vertices = new Vector3[vertices2D.Length]; for (int i = 0; i < vertices.Length; i++) { vertices[i] = new Vector3(vertices2D[i].x, vertices2D[i].y, 0); } // Create the mesh Mesh msh = new Mesh(); msh.vertices = vertices; msh.triangles = indices; msh.RecalculateNormals(); msh.RecalculateBounds(); // Set up game object with mesh; gameObject.AddComponent(typeof(MeshRenderer)); MeshFilter filter = gameObject.GetComponent <MeshFilter>(); if (filter == null) { filter = gameObject.AddComponent(typeof(MeshFilter)) as MeshFilter; } filter.mesh = msh; }
private void convertVariables(Root root) { foreach (var VARIABLE in root.crossRoads) { polygons.Add(new List <Vector3>()); } if (root.lanes != null) { foreach (var lane in root.lanes) { GameObject prefab; if (lane.way == -1 || lane.way == 1) { prefab = BothCollider; } else { prefab = Blocked; } GameObject obj = Instantiate(prefab) as GameObject; Transform transform = obj.GetComponent <Transform>(); Vector3 position = new Vector3 { x = lane.x, y = lane.y }; Vector3 angle = new Vector3 { x = lane.anglex, y = lane.angley, z = lane.anglez }; Vector3 scale = new Vector3 { x = lane.scalex, y = lane.scaley }; transform.SetPositionAndRotation(position, new Quaternion(0, 0, 0, 0)); print(angle); transform.eulerAngles = angle; transform.localScale = scale; } } if (root.cars != null) { foreach (var jsoncar in root.cars) { GameObject prefab = this.car; GameObject obj = Instantiate(prefab) as GameObject; Transform transform = obj.GetComponent <Transform>(); Vector3 position = new Vector3 { x = jsoncar.x, y = jsoncar.y }; Vector3 angle = new Vector3 { x = 0, y = 0, z = jsoncar.angle }; transform.SetPositionAndRotation(position, new Quaternion(0, 0, 0, 0)); transform.eulerAngles = angle; } } if (root.carCreators != null) { foreach (var creator in root.carCreators) { GameObject prefab = this.carCreator; GameObject obj = Instantiate(prefab) as GameObject; var carCreator = obj.GetComponent <global::CarCreator>(); var points = new List <Vector2>(); foreach (var n in creator.points) { points.Add(new Vector2(n.x, n.y)); } carCreator.list = points; carCreator.angle = creator.angle; carCreator.x = creator.x; carCreator.y = creator.y; carCreator.interval = creator.interval; carCreator.car = this.car; carCreator.creatorName = creator.name; carCreator.angleStart = creator.angleStart; carCreator.angleEnd = creator.angleEnd; Transform transform = obj.GetComponent <Transform>(); Vector3 position = new Vector3 { x = creator.x, y = creator.y }; transform.SetPositionAndRotation(position, new Quaternion(0, 0, 0, 0)); } } if (root.carDestroyers != null) { foreach (var destroyer in root.carDestroyers) { GameObject prefab = this.carDestroyer; GameObject obj = Instantiate(prefab) as GameObject; Transform transform = obj.GetComponent <Transform>(); Vector3 position = new Vector3 { x = destroyer.x, y = destroyer.y }; Vector3 angle = new Vector3 { x = 0, y = 0, z = destroyer.angle }; Vector3 scale = new Vector3 { x = destroyer.scalex, y = destroyer.scaley }; transform.SetPositionAndRotation(position, new Quaternion(0, 0, 0, 0)); // transform.RotateAround(middle, Vector3.forward, angle); transform.localScale = scale; transform.eulerAngles = angle; } } Vector3 start = new Vector3(); Vector3 end = new Vector3(); foreach (var street in root.streets) { start.x = //Camera.main.pixelWidth * root.crossRoads[street.crossRoadFrom].x * 1f - 52.5f; start.y = //Camera.main.pixelHeight * root.crossRoads[street.crossRoadFrom].y * 1f - 52.5f; start.z = 0f; end.x = //Camera.main.pixelWidth * root.crossRoads[street.crossRoadTo].x * 1f - 52.5f; end.y = //Camera.main.pixelHeight * root.crossRoads[street.crossRoadTo].y * 1f - 52.5f; end.z = 0f; start.z = 0; end.z = 0; polygons[street.crossRoadFrom].Add(Camera.main.ScreenToWorldPoint(start) + end - start); polygons[street.crossRoadTo].Add(Camera.main.ScreenToWorldPoint(end) + start - end); createStreet(start, end, street.lanes); } foreach (var cross in root.crossRoads) { GameObject crs = genericCrossRoad; GameObject crossroad2 = Instantiate(crs) as GameObject; Transform crossroadTransform2 = crossroad2.GetComponent <Transform>(); crossroadTransform2.SetPositionAndRotation(new Vector3 { x = cross.x, y = cross.y }, new Quaternion(0, 0, 0, 0)); if (root.lanes == null) { crossroadTransform2.localScale += new Vector3(4f, 4f, 0); } } foreach (var polygon in polygons) { List <Vector2> vertices2D = new List <Vector2>(); foreach (var verticle in polygon) { vertices2D.Add(new Vector2 { x = verticle.x, y = verticle.y }); } Triangulator tr = new Triangulator(vertices2D.ToArray()); int[] indices = tr.Triangulate(); Mesh msh = new Mesh(); msh.vertices = polygon.ToArray(); msh.triangles = indices; msh.RecalculateNormals(); msh.RecalculateBounds(); MeshFilter filter = GetComponent <MeshFilter>(); MeshRenderer renderer = GetComponent <MeshRenderer>(); filter.mesh = msh; } }
void Update() { vertices.Clear(); // ######################################## // PHASE 1 : CALCULATE VERTICES // ######################################## float from = (Quaternion.Euler(0, fovBegin, 0) * transform.rotation).eulerAngles.y * Mathf.Deg2Rad; float to = (Quaternion.Euler(0, fovEnd, 0) * transform.rotation).eulerAngles.y * Mathf.Deg2Rad; UnityEngine.Profiling.Profiler.BeginSample("Recursive raycasting"); CastRays(from, to); UnityEngine.Profiling.Profiler.EndSample(); UnityEngine.Profiling.Profiler.BeginSample("Duplicates removing"); for (int i = vertices.Count - 1; i > 0; i--) { Vector2 relative = new Vector2(vertices[i - 1].x - vertices[i].x, vertices[i - 1].y - vertices[i].y); if (relative.SqrMagnitude() < EPSYLON) { vertices.RemoveAt(i); } } UnityEngine.Profiling.Profiler.EndSample(); UnityEngine.Profiling.Profiler.BeginSample("Vertices interpolation"); // Calculate intermediate vertices (we need a multiple of 3) vertices.Add(new Vector3(0, 0, 0)); int differenceToMultiple = Mathf.Abs((3 - ((vertices.Count) % 3)) % 3); for (int i = 1; i <= differenceToMultiple; i++) { vertices.Add(new Vector2((float)(i) * vertices[0].x / (float)(differenceToMultiple + 1), (float)(i) * vertices[0].y / (float)(differenceToMultiple + 1))); } UnityEngine.Profiling.Profiler.EndSample(); // ############################################ // PHASE 2 : GENERATE MESH TRIANGLES // ############################################ UnityEngine.Profiling.Profiler.BeginSample("Triangulation"); Triangulator triangulator = new Triangulator(vertices); int[] triangles = triangulator.Triangulate(); UnityEngine.Profiling.Profiler.EndSample(); // ############################################ // PHASE 3 : UPDATE MESH VERTICES AND TRIANGLES // ############################################ UnityEngine.Profiling.Profiler.BeginSample("Mesh updating"); Vector3[] vertices3 = new Vector3[vertices.Count]; for (int i = 0; i < vertices3.Length; i++) { vertices3[i] = new Vector3(vertices[i].x, 0f, vertices[i].y); } lightMesh.triangles = new int[0]; lightMesh.vertices = vertices3; lightMesh.triangles = triangles; lightMesh.normals = new Vector3[vertices3.Length]; lightMesh.uv = new Vector2[vertices3.Length]; // Use this instead if you want lightning on the mesh // lightMesh.RecalculateNormals(); UnityEngine.Profiling.Profiler.EndSample(); }
private void CreateBuilding(Way w) { Mesh roofm = new Mesh(); Mesh wallsm = new Mesh(); Loom.RunAsync(() => { Vector3[] nodes = new Vector3[w.nodes.Count]; Vector2[] xz = new Vector2[w.nodes.Count]; float height = (float)w.nodes[0].northing % 10 + 2.0f; if (w.height != 0) height = w.height; Vector3 centroid = new Vector3(); Loom.QueueOnMainThread(()=>{ Vector3 position; RaycastHit hit; for (int a = 0; a < w.nodes.Count; a++) { Node n = w.nodes[a]; position = new Vector3((float)((n.easthing - offsetPositionX) / precision), 5000, (float)((n.northing - offsetPositionZ) / precision)); float castH = 0; if (Physics.Raycast(position, -Vector3.up, out hit, Mathf.Infinity, layerMask)) { castH = hit.point.y; } nodes[a] = new Vector3(position.x, castH + height, position.z); xz[a] = new Vector2(position.x, position.z); centroid += nodes[a]; } centroid /= w.nodes.Count; centroid.y += 1; Vector2[] xzRoof = new Vector2[w.nodes.Count - 1]; for (int a = 0; a < xzRoof.Length; a++) { xzRoof[a] = xz[a]; } Triangulator tr = new Triangulator(xzRoof); int[] indices = tr.Triangulate(); // Create the mesh Vector2[] uvs = new Vector2[nodes.Length]; for (int a = 0; a < nodes.Length; a++) { if (a < nodes.Length - 1) { uvs[a] = new Vector2(Mathf.Abs(nodes[a].x - nodes[a + 1].x), Mathf.Abs(nodes[a].z - nodes[a + 1].z)); } else { uvs[a] = new Vector2(1, 1); } } // Set up game object with mesh; centroid = new Vector3(centroid.x, centroid.y, centroid.z); BuildingCountourMesh(nodes, wallsm); roofm.vertices = nodes; roofm.triangles = indices; roofm.uv = uvs; roofm.RecalculateNormals(); roofm.RecalculateBounds(); GameObject build = new GameObject(); build.name = w.id.ToString(); build.transform.parent = this.transform; GameObject roof = new GameObject(); //roof.transform.position = new Vector3(0,baseHeight,0); roof.name = (2 * w.id).ToString(); mapManager.mapHash.Add(2 * w.id); wayList.Add(2 * w.id); GameObject walls = new GameObject(); walls.name = (3 * w.id).ToString(); //walls.transform.position = new Vector3(0,baseHeight,0); mapManager.mapHash.Add(3 * w.id); wayList.Add(3 * w.id); if (w.name != null) { GameObject label = new GameObject(); FloatingLabel lb = label.AddComponent<FloatingLabel>(); lb.transform.parent = roof.transform; lb.text = w.name; lb.target = GameObject.FindGameObjectWithTag("Player").transform; lb.transform.position = centroid; } walls.transform.parent = build.transform; roof.transform.parent = build.transform; MeshCollider wallmc = walls.AddComponent<MeshCollider>(); MeshCollider roofmc = roof.AddComponent<MeshCollider>(); walls.AddComponent(typeof(MeshRenderer)); MeshFilter filter = walls.AddComponent(typeof(MeshFilter)) as MeshFilter; filter.mesh = wallsm; walls.GetComponent<MeshRenderer>().material = buildingMaterial; if (w.height != 0) walls.GetComponent<MeshRenderer>().material = Resources.Load("Materials/Real Height Material") as Material; //walls.transform.parent = transform; wallmc.sharedMesh = wallsm; roof.AddComponent(typeof(MeshRenderer)); roof.AddComponent(typeof(MeshCollider)); MeshFilter filter2 = roof.AddComponent(typeof(MeshFilter)) as MeshFilter; filter2.mesh = roofm; roofmc.sharedMesh = roofm; roof.GetComponent<MeshRenderer>().material = buildingMaterial; if (w.height != 0) roof.GetComponent<MeshRenderer>().material = Resources.Load("Materials/Real Height Material") as Material; roof.transform.parent = transform; }); }); }
private void CreateCollider() { List <Vector3> pointsToCollider = new List <Vector3>(); foreach (Point p in pointsHulled) { Vector3 newPoint = wall.transform.InverseTransformPoint(new Vector3((float)p.x, (float)p.y, wall.transform.position.z - 0.1f)); pointsToCollider.Add(newPoint); } Triangulator tr = new Triangulator(pointsToCollider.ToArray()); int[] indices = tr.Triangulate(); Vector2[] pointsToCollider2D = new Vector2[pointsToCollider.Count]; int i = 0; foreach (Vector3 points in pointsToCollider) { pointsToCollider2D[i] = new Vector2(points.x, points.y); i++; } // Create PolygonCollider2D /*PolygonCollider2D polygonCollider = wall.AddComponent<PolygonCollider2D>(); * polygonCollider.points = pointsToCollider2D; */ //FOR TEEST ONLY if (wall.gameObject.GetComponent <PolygonCollider2D>() == null) { wall.gameObject.AddComponent <PolygonCollider2D>().points = pointsToCollider2D; } else { wall.gameObject.GetComponent <PolygonCollider2D>().points = pointsToCollider2D; } if (Real2DBackground.gameObject.GetComponent <PolygonCollider2D>() == null) { Real2DBackground.gameObject.AddComponent <PolygonCollider2D>().points = pointsToCollider2D; } else { Real2DBackground.gameObject.GetComponent <PolygonCollider2D>().points = pointsToCollider2D; } //Create the mesh Mesh msh = new Mesh(); msh.vertices = pointsToCollider.ToArray(); msh.triangles = indices; msh.RecalculateNormals(); msh.RecalculateBounds(); if (Real2DBackground.childCount > 0) { foreach (Transform Child in Real2DBackground) { Destroy(Child.gameObject); } } //Set up game object with mesh; GameObject objectMesh = new GameObject(); objectMesh.transform.parent = Real2DBackground.transform; //objectMesh.transform.position = new Vector3(wall.transform.position.x, wall.transform.position.y, wall.transform.position.z); objectMesh.transform.position = Real2DBackground.gameObject.GetComponent <PolygonCollider2D>().bounds.center; objectMesh.transform.localScale = new Vector3(1, 1, 1); objectMesh.gameObject.AddComponent(typeof(MeshRenderer)); MeshFilter filter = objectMesh.AddComponent(typeof(MeshFilter)) as MeshFilter; filter.mesh = msh; float difX = objectMesh.transform.position.x - objectMesh.GetComponent <Renderer>().bounds.center.x; float difY = objectMesh.transform.position.y - objectMesh.GetComponent <Renderer>().bounds.center.y; float difZ = objectMesh.transform.position.z - objectMesh.GetComponent <Renderer>().bounds.center.z; objectMesh.transform.position = new Vector3(objectMesh.transform.position.x + difX, objectMesh.transform.position.y + difY, objectMesh.transform.position.z + difZ - 0.8f); }
// Use this for initialization void Start() { int nvertex = 4; float extrude_length = 5.0f; Vector2[] pos = new Vector2[nvertex]; pos[0] = new Vector2(-1, -1); pos[1] = new Vector2(1, -1); pos[2] = new Vector2(1, 1); pos[3] = new Vector2(-1, 1); // Use triangulator to get indices for creating triangles Triangulator tr = new Triangulator(pos); int[] indices = tr.Triangulate(); // Create the Vector3 vertices Vector3[] vertices = new Vector3[pos.Length]; for (int j = 0; j < vertices.Length; j++) { vertices[j] = new Vector3(pos[j].x, 0, pos[j].y); } // Create the mesh Mesh msh = new Mesh(); msh.vertices = vertices; msh.triangles = indices; msh.RecalculateNormals(); msh.RecalculateBounds(); float[] length = new float[vertices.Length]; float net_length = 0; for (int j = 0; j < vertices.Length; j++) { if (j < vertices.Length - 1) { length[j] = (vertices[j] - vertices[j + 1]).magnitude; net_length += length[j]; } else { length[j] = (vertices[j] - vertices[0]).magnitude; net_length += length[j]; } } Vector3[] tvertices = msh.vertices; Vector2[] uvs = new Vector2[tvertices.Length]; float cummulated_length = 0; for (int j = 0; j < uvs.Length; j++) { //uvs[j] = new Vector2 (vertices[j].x, vertices[j].z); uvs[j] = new Vector2(cummulated_length / net_length, 0); cummulated_length += length[j]; } msh.uv = uvs; Matrix4x4[] finalSections = new Matrix4x4[2]; finalSections[0] = Matrix4x4.identity; finalSections[1] = Matrix4x4.TRS(new Vector3(0, extrude_length, 0), Quaternion.identity, Vector3.one); MeshExtrusion.Edge[] precomputedEdges = MeshExtrusion.BuildManifoldEdges(msh); MeshExtrusion.ExtrudeMesh(msh, msh, finalSections, precomputedEdges, true); // Set up game object with mesh; GameObject extruded_object = new GameObject(); MeshFilter filter = extruded_object.AddComponent <MeshFilter>(); filter.mesh = msh; MeshRenderer mr = extruded_object.AddComponent <MeshRenderer>(); mr.material = mtl; MeshCollider mc = extruded_object.AddComponent <MeshCollider>(); //mc.sharedMesh = null; mc.sharedMesh = msh; }
/** * Materializes the currently drawn object; if successful, the corresponding cutout will also be created. * If the object cannot be materialized, this does nothing. */ public void MaterializeObject(List <Vector3> points) { //if the object was not close enough to a loop, do not create it if (Vector3.Distance(points[points.Count - 1], points[0]) > loopThreshold) { Debug.Log("not a loop"); return; } //otherwise, create the object polygon = Instantiate(drawnPrefab, this.gameObject.transform); polygon.tag = "Drawn"; //make the outline lrenderer = polygon.GetComponent <LineRenderer>(); lrenderer.useWorldSpace = false; lrenderer.positionCount = points.Count; lrenderer.SetPositions(points.ToArray()); //create rigidbody, collider and fill shape rb = polygon.GetComponent <Rigidbody2D>(); pCollider = polygon.GetComponent <PolygonCollider2D>(); pCollider.points = ConvertTo2DLoop(points); pCollider.density = density; //prepare to add mesh to fill object MeshFilter meshFilter = polygon.GetComponent <MeshFilter>(); Mesh mesh = new Mesh(); MeshRenderer meshRenderer = polygon.GetComponent <MeshRenderer>(); //initialization for the Triangulator, to create the mesh Vector2[] points2d = new Vector2[points.Count + 1]; for (int i = 0; i < points.Count; i++) { points2d[i] = (Vector2)points[i]; } points2d[points2d.Length - 1] = points[0]; //make it loop back around points2d[points2d.Length - 1].x += 0.01f; Vector3[] vertices = new Vector3[points2d.Length]; Vector2[] uv = new Vector2[points2d.Length]; for (int i = 0; i < points2d.Length; i++) { Vector2 point = points2d[i]; vertices[i] = new Vector3(point.x, point.y, 0); uv[i] = point; } //set the fill color Color[] colors = new Color[points2d.Length]; for (int i = 0; i < points2d.Length; i++) { colors[i] = Color.white; } Triangulator tr = new Triangulator(points2d); int [] triangles = tr.Triangulate(); //get triangles for the mesh using the Triangulator mesh.vertices = vertices; mesh.triangles = triangles; mesh.uv = uv; mesh.colors = colors; //assign mesh to MeshFilter meshFilter.mesh = mesh; mesh.RecalculateBounds(); //create white cutout on background CreateCutout(pCollider.points); GameObject.FindGameObjectsWithTag("GameController")[0].GetComponent <GameController>().ActivateRandomDrawArea(); Debug.Log("materialized"); }
private void CreateMesh() { // Create Vector2 vertices List <Vector2> controls = new List <Vector2>(); controls.Add(new Vector2(0, invert ? 5f : -5f)); float x = 0; float y = invert ? -1f : 1f; bool wall = false; while (x < _length) { float dx; if (wall) { dx = Random.Range(0.2f, 1f); wall = false; } else { dx = Random.value > 0.5f ? Random.Range(0.2f, 1f) : 0; wall = dx == 0; } float dy; do { dy = (wall ? Random.Range(-1f, 1f) : (Random.Range(-1, 2)) * dx); } while (invert ? (y + dy > -0.5f || y + dy < -height) : (y + dy < 0.5f || y + dy > height)); x += dx; y += dy; controls.Add(new Vector2(x, y)); } controls.Add(new Vector2(x, invert ? 5f : -5f)); var vertices2D = controls.ToArray(); var vertices3D = System.Array.ConvertAll <Vector2, Vector3>(vertices2D, v => v); // Use the triangulator to get indices for creating triangles var triangulator = new Triangulator(vertices2D); var indices = triangulator.Triangulate(); // if (!invert) { // Array.Reverse(indices); // } // Generate a color for each vertex var colors = Enumerable.Range(0, vertices3D.Length) .Select(i => Random.ColorHSV()) .ToArray(); // Create the mesh var mesh = new Mesh { vertices = vertices3D, triangles = indices, colors = colors, uv = vertices2D }; mesh.RecalculateNormals(); mesh.RecalculateBounds(); GetComponent <MeshFilter>().mesh = mesh; GetComponent <PolygonCollider2D>().points = vertices2D; }
protected void SetIndices() { LoopedList<Point2> points = _polygon.GetPoints (); int indicesCount = points.Count * 6; int sideCount = indicesCount; int [] indices = new int[indicesCount]; if (_upCap || _bottomCap) { Vector2 [] cap = _polygon.ToVector2Array (); // indices des bouchons calcculé grace a la triangulation Triangulator tr = new Triangulator (cap); int [] capIndices = tr.Triangulate (); int capIndicesIndex = sideCount; int upAndBottomCapCount = capIndices.Length; if (_quantity == 0) { indicesCount = 0; sideCount = 0; capIndicesIndex = 0; } if (_upCap) { indicesCount += upAndBottomCapCount; } if (_bottomCap) { indicesCount += upAndBottomCapCount; } indices = new int [indicesCount]; int upCapOffset = 0; if (_upCap) { if (_quantity != 0) { upCapOffset = points.Count * 2; } for (int upCapIndex = 0; capIndicesIndex < sideCount + upAndBottomCapCount - 2; capIndicesIndex += 3, upCapIndex += 3) { if (!_inverseNormal) { indices[capIndicesIndex] = capIndices[upCapIndex] + upCapOffset; indices[capIndicesIndex + 1] = capIndices[upCapIndex + 1] + upCapOffset; indices[capIndicesIndex + 2] = capIndices[upCapIndex + 2] + upCapOffset; } else { indices[capIndicesIndex] = capIndices[upCapIndex] + upCapOffset; indices[capIndicesIndex + 1] = capIndices[upCapIndex + 2] + upCapOffset; indices[capIndicesIndex + 2] = capIndices[upCapIndex + 1] + upCapOffset; } } } if (_bottomCap) { capIndicesIndex = indicesCount - upAndBottomCapCount; int bottomOffset = upCapOffset; if (_quantity != 0) { if (bottomOffset == 0) { bottomOffset = points.Count * 2; } else { bottomOffset += points.Count; } } for (int bottomCapIndex = 0; capIndicesIndex < indicesCount - 2; capIndicesIndex += 3, bottomCapIndex += 3) { if (_inverseNormal) { indices[capIndicesIndex] = capIndices[bottomCapIndex] + bottomOffset; indices[capIndicesIndex + 1] = capIndices[bottomCapIndex + 1] + bottomOffset; indices[capIndicesIndex + 2] = capIndices[bottomCapIndex + 2] + bottomOffset; } else { indices[capIndicesIndex] = capIndices[bottomCapIndex] + bottomOffset; indices[capIndicesIndex + 1] = capIndices[bottomCapIndex + 2] + bottomOffset; indices[capIndicesIndex + 2] = capIndices[bottomCapIndex + 1] + bottomOffset; } } } } if (_quantity != 0) { int indicesIndex = 0; for (int pointIndex = 0; pointIndex < points.Count * 2 - 2; indicesIndex += 6, pointIndex += 2) { if (!_inverseNormal) { indices[indicesIndex] = pointIndex; indices[indicesIndex + 1] = pointIndex + 1; indices[indicesIndex + 2] = pointIndex + 2; indices[indicesIndex + 3] = pointIndex + 1; indices[indicesIndex + 4] = pointIndex + 3; indices[indicesIndex + 5] = pointIndex + 2; } else { indices[indicesIndex] = pointIndex; indices[indicesIndex + 1] = pointIndex + 2; indices[indicesIndex + 2] = pointIndex + 1; indices[indicesIndex + 3] = pointIndex + 1; indices[indicesIndex + 4] = pointIndex + 2; indices[indicesIndex + 5] = pointIndex + 3; } } if (_polygon.IsClosed ()) { if (!_inverseNormal) { int pointIndex = points.Count * 2 - 2; int lastIndex = _mesh.vertexCount; indices[indicesIndex] = pointIndex; indices[indicesIndex + 1] = pointIndex + 1; indices[indicesIndex + 2] = lastIndex - 2; indices[indicesIndex + 3] = pointIndex + 1; indices[indicesIndex + 4] = lastIndex - 1; indices[indicesIndex + 5] = lastIndex - 2; } else { int pointIndex = points.Count * 2 - 2; int lastIndex = _mesh.vertexCount; indices[indicesIndex] = pointIndex; indices[indicesIndex + 1] = lastIndex - 2; indices[indicesIndex + 2] = pointIndex + 1; indices[indicesIndex + 3] = pointIndex + 1; indices[indicesIndex + 4] = lastIndex - 2; indices[indicesIndex + 5] = lastIndex - 1; } } } _mesh.triangles = indices; }
void Start() { Vector3[] newVertices = new Vector3[] { new Vector3(0, 0, 10.01f), new Vector3(width, 0, 10.01f), new Vector3(0, height, 10.01f), new Vector3(width, height, 10.01f) }; Vector2[] newUV = new Vector2[] { new Vector2(0, 0), new Vector2(1, 0), new Vector2(0, 1), new Vector2(1, 1) }; int[] newTriangles = new int[] { 0, 2, 1, 2, 3, 1 }; // must be clockwise triangles List <Vector2> verts2d = new List <Vector2>(); List <int> triangles = new List <int> (); float meter = 0; int vertcount = 0; while (meter < angle) { float increment = angle / divisions; Vector2 ov = new Vector2(center.x + outerRadius * Mathf.Sin(increment), center.y + outerRadius * Mathf.Cos(increment)); Vector2 iv = new Vector2(center.x + innerRadius * Mathf.Sin(increment), center.y + innerRadius * Mathf.Cos(increment)); verts2d.Add(ov); verts2d.Add(iv); if (vertcount % 2 == 0 && vertcount > 0) { triangles.Add(vertcount - 2); triangles.Add(vertcount); triangles.Add(vertcount - 1); } else if (vertcount % 2 == 1 && vertcount > 1) { triangles.Add(vertcount - 2); triangles.Add(vertcount - 1); triangles.Add(vertcount); } meter += increment; vertcount += 1; } Vector2[] verts2 = new Vector2[verts2d.Count]; Vector3[] verts3 = new Vector3[verts2d.Count]; for (int i = 0; i < verts2d.Count; i++) { verts2 [i] = new Vector2(verts2d [i].x, verts2d [i].y); verts3 [i] = new Vector3(verts2d [i].x, verts2d [i].y, z); } int[] triangs = new int[triangles.Count]; for (int j = 0; j < triangles.Count; j++) { triangs [j] = triangles [j]; } Triangulator tr = new Triangulator(verts2); int[] indices = tr.Triangulate(); Mesh mesh = new Mesh(); GetComponent <MeshFilter>().mesh = mesh; Debug.Log(verts3.Length); Debug.Log(triangs.Length); mesh.vertices = verts3; mesh.triangles = triangs; }
public static Mesh CreateMesh3D(Vector2[] poly, float extrusion) { // convert polygon to triangles Triangulator triangulator = new Triangulator(poly); int[] traingulatedTris = triangulator.Triangulate(); Mesh m = new Mesh(); Vector3[] vertices; if (extrusion == 0f) { vertices = new Vector3[poly.Length]; } else { vertices = new Vector3[poly.Length * 2]; } for (int i = 0; i < poly.Length; i++) { vertices [i].x = poly [i].x; vertices [i].y = poly [i].y; vertices [i].z = -extrusion; // front vertex if (extrusion != 0f) { vertices [i + poly.Length].x = poly [i].x; vertices [i + poly.Length].y = poly [i].y; vertices [i + poly.Length].z = extrusion; // back vertex } } int[] triangles; if (extrusion == 0f) { triangles = new int[traingulatedTris.Length]; } else { triangles = new int[traingulatedTris.Length * 2 + poly.Length * 6]; } int count_tris = 0; for (int i = 0; i < traingulatedTris.Length; i += 3) { triangles [i] = traingulatedTris [i]; triangles [i + 1] = traingulatedTris [i + 1]; triangles [i + 2] = traingulatedTris [i + 2]; } // front vertices if (extrusion != 0f) { count_tris += traingulatedTris.Length; for (int i = 0; i < traingulatedTris.Length; i += 3) { triangles [count_tris + i] = traingulatedTris [i + 2] + poly.Length; triangles [count_tris + i + 1] = traingulatedTris [i + 1] + poly.Length; triangles [count_tris + i + 2] = traingulatedTris [i] + poly.Length; } // back vertices } //texture coordinate Vector2[] uvs = new Vector2[vertices.Length]; for (int i = 0, c = uvs.Length; i < c; ++i) { uvs[i].x = vertices[i].x; uvs[i].y = vertices[i].y; } m.vertices = vertices; m.triangles = triangles; m.uv = uvs; if (extrusion != 0f) { m = Triangulator.SideExtrusion(m); } m.RecalculateNormals(); m.RecalculateBounds(); m.Optimize(); return(m); }
public void RefreshPhysics() { //Debug.Log("RefreshPhysics"); if (boxColliders == null && GetPhysics() == Physics.Boxed) { boxColliders = new BoxCollider[1]; } if (!Application.isPlaying && !GetCreatePhysicsInEditor()) { DestroyPhysicsChildren(); } if (Application.isPlaying || GetCreatePhysicsInEditor()) { switch (GetPhysics()) { case Physics.None: DestroyPhysicsChildren(); break; case Physics.Boxed: DestroyMeshCollider(); if (lastPhysicsVertsCount != GetSplits(physicsColliderCount, 0f, 1f).Length || boxColliders[0] == null) { if (!Application.isPlaying) { DestroyPhysicsChildren(); } lastPhysicsVertsCount = GetSplits(physicsColliderCount, 0f, 1f).Length; RageVertex[] splits = new RageVertex[0]; splits = GetSplits(physicsColliderCount, 0f, 1f); boxColliders = new BoxCollider[splits.Length - 1]; int t = 0; t = splits.Length - 1; for (int i = 0; i < t; i++) { GameObject newObj = new GameObject(); newObj.name = "ZZZ_" + gameObject.name + "_BoxCollider"; newObj.transform.parent = transform; BoxCollider box = newObj.AddComponent(typeof(BoxCollider)) as BoxCollider; box.material = GetPhysicsMaterial(); int i2 = i + 1; Vector3 pos; Vector3 pos2; Vector3 norm = GetNormal(splits[i].splinePosition); Vector3 norm2 = GetNormal(splits[i2].splinePosition); pos = splits[i].position - norm * (GetBoxColliderDepth() * 0.5f - GetPhysicsNormalOffset()); pos2 = splits[i2].position - norm2 * (GetBoxColliderDepth() * 0.5f - GetPhysicsNormalOffset()); newObj.layer = transform.gameObject.layer; newObj.tag = transform.gameObject.tag; newObj.gameObject.transform.localPosition = (pos + pos2) * 0.5f; newObj.gameObject.transform.LookAt(transform.TransformPoint(newObj.gameObject.transform.localPosition + Vector3.Cross((pos - pos2).normalized, new Vector3(0f, 0f, -1f))), new Vector3(1f, 0f, 0f)); newObj.gameObject.transform.localScale = new Vector3(GetPhysicsZDepth(), ((pos + norm * GetBoxColliderDepth() * 0.5f) - (pos2 + norm2 * GetBoxColliderDepth() * 0.5f)).magnitude, 1f * GetBoxColliderDepth()); boxColliders[i] = box; } } else { int i = 0; RageVertex[] splits = new RageVertex[0]; splits = GetSplits(GetPhysicsColliderCount(), 0f, 1f); foreach (BoxCollider obj in boxColliders) { obj.material = GetPhysicsMaterial(); int i2 = i + 1; Vector3 norm = GetNormal(splits[i].splinePosition); Vector3 norm2 = GetNormal(splits[i2].splinePosition); Vector3 pos; Vector3 pos2; pos = splits[i].position - norm * (GetBoxColliderDepth() * 0.5f - GetPhysicsNormalOffset()); pos2 = splits[i2].position - norm2 * (GetBoxColliderDepth() * 0.5f - GetPhysicsNormalOffset()); obj.gameObject.transform.localPosition = (pos + pos2) * 0.5f; obj.gameObject.transform.LookAt(transform.TransformPoint(obj.gameObject.transform.localPosition + Vector3.Cross((pos - pos2).normalized, new Vector3(0f, 0f, -1f))), new Vector3(1f, 0f, 0f)); obj.gameObject.transform.localScale = new Vector3(GetPhysicsZDepth(), ((pos + norm * GetBoxColliderDepth() * 0.5f) - (pos2 + norm2 * GetBoxColliderDepth() * 0.5f)).magnitude, 1f * GetBoxColliderDepth()); i++; } lastPhysicsVertsCount = physicsColliderCount; } break; case Physics.MeshCollider: DestroyBoxColliders(); if (GetPhysicsColliderCount() > 2 && (GetCreatePhysicsInEditor() || Application.isPlaying)) { Vector3[] verts = null; RageVertex[] splits2 = null; int[] tris = null; int tt = 0; if (GetFill() != Fill.Landscape) { splits2 = GetSplits(GetPhysicsColliderCount(), 0f, 1f); verts = new Vector3[splits2.Length * 2]; //verts = new Vector3[GetPhysicsColliderCount() * 2]; tris = new int[verts.Length * 3 + (verts.Length - 2) * 6]; //splits2 = GetSplits(GetPhysicsColliderCount(), 0f, 1f); for (int v = 0; v < verts.Length; v += 2) { verts[v] = splits2[v / 2].position + new Vector3(0f, 0f, GetPhysicsZDepth() * 0.5f) + GetNormal(splits2[v / 2].splinePosition) * GetPhysicsNormalOffset(); verts[v + 1] = splits2[v / 2].position + new Vector3(0f, 0f, GetPhysicsZDepth() * -0.5f) + GetNormal(splits2[v / 2].splinePosition) * GetPhysicsNormalOffset(); if (v < verts.Length - 2) { tris[tt + 0] = v + 0; tris[tt + 1] = v + 2; tris[tt + 2] = v + 1; tris[tt + 3] = v + 1; tris[tt + 4] = v + 2; tris[tt + 5] = v + 3; } else { tris[tt + 0] = v + 0; tris[tt + 1] = 0; tris[tt + 2] = v + 1; tris[tt + 3] = v + 1; tris[tt + 4] = 0; tris[tt + 5] = 1; } tt += 6; } } else { splits2 = GetSplits(GetPhysicsColliderCount(), 0f, 1f); verts = new Vector3[splits2.Length * 2 + 4]; tris = new int[verts.Length * 3 + (verts.Length - 2) * 6]; //verts = new Vector3[GetPhysicsColliderCount() * 2 + 4]; //tris = new int[verts.Length * 3 + (verts.Length - 2) * 6]; //splits2 = GetSplits(GetPhysicsColliderCount() - 1, 0f, 1f); float bottomY = GetBounds().yMin - Mathf.Clamp(GetLandscapeBottomDepth(), 1f, 100000000f); verts[0] = new Vector3(splits2[0].position.x, bottomY, GetPhysicsZDepth() * 0.5f); verts[1] = new Vector3(splits2[0].position.x, bottomY, GetPhysicsZDepth() * -0.5f); for (int v = 2; v < verts.Length - 2; v += 2) { verts[v] = splits2[(v - 2) / 2].position + new Vector3(0f, 0f, GetPhysicsZDepth() * 0.5f) + GetNormal(splits2[(v - 2) / 2].splinePosition) * GetPhysicsNormalOffset(); verts[v + 1] = splits2[(v - 2) / 2].position + new Vector3(0f, 0f, GetPhysicsZDepth() * -0.5f) + GetNormal(splits2[(v - 2) / 2].splinePosition) * GetPhysicsNormalOffset(); } for (int v = 0; v < verts.Length; v += 2) { if (v < verts.Length - 2) { tris[tt + 0] = v + 0; tris[tt + 1] = v + 2; tris[tt + 2] = v + 1; tris[tt + 3] = v + 1; tris[tt + 4] = v + 2; tris[tt + 5] = v + 3; } else { tris[tt + 0] = v + 0; tris[tt + 1] = 0; tris[tt + 2] = v + 1; tris[tt + 3] = v + 1; tris[tt + 4] = 0; tris[tt + 5] = 1; } tt += 6; } verts[verts.Length - 2] = new Vector3(splits2[splits2.Length - 1].position.x, bottomY, GetPhysicsZDepth() * 0.5f); verts[verts.Length - 1] = new Vector3(splits2[splits2.Length - 1].position.x, bottomY, GetPhysicsZDepth() * -0.5f); } Vector2[] pverts = new Vector2[verts.Length / 2]; for (int i = 0; i < pverts.Length; i++) { pverts[i] = new Vector2(verts[i * 2].x, verts[i * 2].y); } Vector2[] pverts2 = new Vector2[verts.Length / 2]; for (int i = 0; i < pverts2.Length; i++) { pverts2[i] = new Vector2(verts[i * 2 + 1].x, verts[i * 2 + 1].y); } Triangulator triangulator = new Triangulator(pverts); int[] fillTris = triangulator.Triangulate(); //for (int i = fillTris.Length - 1; i >= 0; i--) for (int i = 0; i < fillTris.Length; i++) { tris[tt++] = fillTris[i] * 2; } Triangulator triangulator2 = new Triangulator(pverts2); int[] fillTris2 = triangulator2.Triangulate(); //for (int i = 0; i < fillTris2.Length; i++) for (int i = fillTris2.Length-1; i >= 0; i--) { tris[tt++] = fillTris2[i] * 2 + 1; } MeshCollider meshCollider = gameObject.GetComponent(typeof(MeshCollider)) as MeshCollider; bool wasNull = false; if (meshCollider == null) { wasNull = true; } Mesh colMesh = null; if (wasNull) { colMesh = new Mesh(); } else { if (meshCollider.sharedMesh != null) { colMesh = meshCollider.sharedMesh; } else { colMesh = new Mesh(); } } colMesh.Clear(); colMesh.vertices = verts; colMesh.triangles = tris; colMesh.RecalculateBounds(); colMesh.RecalculateNormals(); colMesh.Optimize(); if (wasNull) { //MeshFilter filter = gameObject.GetComponent(typeof(MeshFilter)) as MeshFilter; meshCollider = gameObject.AddComponent(typeof(MeshCollider)) as MeshCollider; } meshCollider.sharedMesh = null; meshCollider.sharedMesh = colMesh; meshCollider.sharedMaterial = physicsMaterial; meshCollider.convex = GetCreateConvexMeshCollider(); } break; case Physics.OutlineMeshCollider: DestroyBoxColliders(); if (GetPhysicsColliderCount() > 2 && (GetCreatePhysicsInEditor() || Application.isPlaying)) { int splitCount = GetPhysicsColliderCount(); Vector3[] verts = new Vector3[(splitCount + 1) * 4]; int[] tris = new int[splitCount * 24]; int v = 0; for (int i = 0; i <= splitCount; i++) { float splinePos = (float)i / (float)splitCount; Vector3 normal = GetNormal(splinePos); verts[v++] = GetPosition(splinePos) + normal * GetOutlineWidth() * 0.5f + normal * GetOutlineNormalOffset() + new Vector3(0f, 0f, GetPhysicsZDepth() * 0.5f); verts[v++] = GetPosition(splinePos) + normal * GetOutlineWidth() * -0.5f + normal * GetOutlineNormalOffset() + new Vector3(0f, 0f, GetPhysicsZDepth() * 0.5f); verts[v++] = GetPosition(splinePos) + normal * GetOutlineWidth() * -0.5f + normal * GetOutlineNormalOffset() - new Vector3(0f, 0f, GetPhysicsZDepth() * 0.5f); verts[v++] = GetPosition(splinePos) + normal * GetOutlineWidth() * 0.5f + normal * GetOutlineNormalOffset() - new Vector3(0f, 0f, GetPhysicsZDepth() * 0.5f); } int t = 0; for (int i = 0; i < splitCount; i++) { tris[t++] = i * 4 + 0; tris[t++] = i * 4 + 0 + 4 + 1; tris[t++] = i * 4 + 0 + 4; tris[t++] = i * 4 + 0; tris[t++] = i * 4 + 0 + 1; tris[t++] = i * 4 + 0 + 4 + 1; tris[t++] = i * 4 + 1; tris[t++] = i * 4 + 1 + 4 + 1; tris[t++] = i * 4 + 1 + 4; tris[t++] = i * 4 + 1; tris[t++] = i * 4 + 1 + 1; tris[t++] = i * 4 + 1 + 4 + 1; tris[t++] = i * 4 + 2; tris[t++] = i * 4 + 2 + 4 + 1; tris[t++] = i * 4 + 2 + 4; tris[t++] = i * 4 + 2; tris[t++] = i * 4 + 2 + 1; tris[t++] = i * 4 + 2 + 4 + 1; tris[t++] = i * 4 + 3; tris[t++] = i * 4 + 3 + 1; tris[t++] = i * 4 + 3 + 4; tris[t++] = i * 4 + 3; tris[t++] = i * 4; tris[t++] = i * 4 + 3 + 1; /* tris[t++] = i * 4 + 0; tris[t++] = i * 4 + 0 + 4; tris[t++] = i * 4 + 0 + 4 + 1; tris[t++] = i * 4 + 0; tris[t++] = i * 4 + 0 + 4 + 1; tris[t++] = i * 4 + 0 + 1; tris[t++] = i * 4 + 1; tris[t++] = i * 4 + 1 + 4; tris[t++] = i * 4 + 1 + 4 + 1; tris[t++] = i * 4 + 1; tris[t++] = i * 4 + 1 + 4 + 1; tris[t++] = i * 4 + 1 + 1; tris[t++] = i * 4 + 2; tris[t++] = i * 4 + 2 + 4; tris[t++] = i * 4 + 2 + 4 + 1; tris[t++] = i * 4 + 2; tris[t++] = i * 4 + 2 + 4 + 1; tris[t++] = i * 4 + 2 + 1; tris[t++] = i * 4 + 3; tris[t++] = i * 4 + 3 + 4; tris[t++] = i * 4 + 3 + 1; tris[t++] = i * 4 + 3; tris[t++] = i * 4 + 3 + 1; tris[t++] = i * 4; */ } MeshCollider meshCollider = gameObject.GetComponent(typeof(MeshCollider)) as MeshCollider; bool wasNull = false; if (meshCollider == null) { wasNull = true; } Mesh colMesh = null; if (wasNull) { colMesh = new Mesh(); } else { if (meshCollider.sharedMesh != null) { colMesh = meshCollider.sharedMesh; } else { colMesh = new Mesh(); } } colMesh.Clear(); colMesh.vertices = verts; colMesh.triangles = tris; colMesh.RecalculateBounds(); colMesh.RecalculateNormals(); colMesh.Optimize(); if (wasNull) { //MeshFilter filter = gameObject.GetComponent(typeof(MeshFilter)) as MeshFilter; meshCollider = gameObject.AddComponent(typeof(MeshCollider)) as MeshCollider; } meshCollider.sharedMesh = null; meshCollider.sharedMesh = colMesh; meshCollider.sharedMaterial = physicsMaterial; meshCollider.convex = GetCreateConvexMeshCollider(); } break; } } }
public void CreateSideWalks(List <GameObject> streetWeb, List <List <Vector3> > streetsPoly) { List <GameObject> sideWalks = new List <GameObject>(); for (int i = 0; i < streetWeb.Count; i++) { GameObject sideWalk = new GameObject("sideWalk", typeof(MeshRenderer), typeof(MeshFilter)); sideWalk.transform.parent = this.transform; sideWalk.GetComponent <MeshRenderer>().material = (Material)Resources.Load("SideWalkMat"); List <List <IntPoint> > solution = new List <List <IntPoint> >(); //transform vertices of each mesh in points for clipper //List<IntPoint> intPoint = FromVecToIntPoint(streetWeb[i].GetComponent<MeshFilter>().sharedMesh.vertices); List <IntPoint> intPoint = FromVecToIntPoint(streetsPoly[i].ToArray()); //offset each mesh ClipperOffset co = new ClipperOffset(); co.AddPath(intPoint, JoinType.jtRound, EndType.etOpenRound); co.Execute(ref solution, 1000.0); List <Vector2> vertices2D = new List <Vector2>(); for (int j = 0; j < solution.Count; j++) { vertices2D = vertices2D.Concat(FromIntPointToVec(solution[j])).ToList(); } // Use the triangulator to get indices for creating triangles Triangulator tr = new Triangulator(vertices2D.ToArray()); int[] indices = tr.Triangulate(); // Create the Vector3 vertices Vector3[] vertices = new Vector3[vertices2D.Count]; for (int k = 0; k < vertices.Length; k++) { vertices[k] = new Vector3(vertices2D[k].x, 0f, vertices2D[k].y); } // Create the mesh Mesh msh = new Mesh(); msh.vertices = vertices; msh.triangles = indices; msh.RecalculateNormals(); msh.RecalculateBounds(); // Set up game object with mesh; sideWalk.GetComponent <MeshFilter>().mesh = msh; sideWalks.Add(sideWalk); } //foreach intersectionCluster unify streets and sidewalks and subtract int swNumber = 1; foreach (HashSet <int> cluster in intersectionClusters) { Mesh newMesh = Subtract(UnifyPolygons(sideWalks, "sidewalks", cluster), UnifyPolygons(streetWeb, "streets", cluster)); //build 3D sidewalk List <GameObject> objs = new List <GameObject>(); GameObject sub = new GameObject("unifiedSideWalks", typeof(MeshFilter), typeof(MeshRenderer)); sub.transform.parent = this.transform; sub.GetComponent <MeshRenderer>().material = (Material)Resources.Load("SideWalkMat"); sub.GetComponent <MeshFilter>().mesh = newMesh; objs.Add(sub); GameObject sub1 = new GameObject("unifiedSideWalks", typeof(MeshFilter), typeof(MeshRenderer)); sub1.transform.parent = this.transform; sub1.GetComponent <MeshRenderer>().material = (Material)Resources.Load("SideWalkMat"); sub1.GetComponent <MeshFilter>().mesh = newMesh; sub1.transform.position = new Vector3(0f, 0.2f, 0f); objs.Add(sub1); GameObject sidewalk = new GameObject("sidewalk", typeof(MeshFilter), typeof(MeshRenderer)); sidewalk.transform.parent = this.transform; sidewalk.GetComponent <MeshRenderer>().material = (Material)Resources.Load("SideWalkMat"); sidewalk.GetComponent <MeshFilter>().sharedMesh = MeshOps.CreateSolid(newMesh, 0.15f); objs.Add(sidewalk); UnifyAndClearMesh(objs, "sideWalk" + swNumber, (Material)Resources.Load("SideWalkMat")); swNumber += 1; } foreach (GameObject sw in sideWalks) { DestroyImmediate(sw.gameObject); } }