- Home /
Get quads from mesh? [SOLVED]
I'm trying to make a tile-based game which uses pre-made map meshes. I need to find all of the center point of each quad in the mesh so that I can set up a node graph from it. Unity treats this mesh as triangles, however, so it becomes harder for me to do this. I've attached an image of a basic map which I am trying to use.
How can I find each quad in this mesh? Speed isn't an issue as I'm doing this once in the editor.
EDIT: I've fixed my issue, though I didn't actually find the quads, I used the sides of the triangles to get the midpoint of the quads. I'll post the code below for anyone who has a similar issue to me. The code is probably very inefficient but that doesn't matter to me since it's just for building the nodegraphs.
using UnityEngine;
using System.Collections; using System.Threading; using System.Collections.Generic;
using UnityEngine;
using System.Collections;
using System.Threading;
using System.Collections.Generic;
public class MeshTest : MonoBehaviour {
Mesh mesh;
void Start()
{
Vector3[] mapNodes = GenerateMesh();
}
private Vector3[] GenerateMesh()
{
mesh = gameObject.GetComponent<MeshFilter>().mesh;
Vector3[] vertices = mesh.vertices;
int[] triangles = mesh.triangles;
List<Vector3> finalVerts = new List<Vector3>();
for (int i = 0; i < triangles.Length; i+=3)
{
Vector3 p1 = mesh.vertices[triangles[i+0]];
Vector3 p2 = mesh.vertices[triangles[i+1]];
Vector3 p3 = mesh.vertices[triangles[i+2]];
float d1 = Vector3.Distance(p1,p2);
float d2 = Vector3.Distance(p2,p3);
float d3 = Vector3.Distance(p3,p1);
Vector3 point = Vector3.zero;
if(d1 > d2 && d1 > d3)
point = (p1+p2)/2;
if(d2 > d1 && d2 > d3)
point = (p2+p3)/2;
if(d3 > d1 && d3 > d2)
point = (p3+p1)/2;
if(point != Vector3.zero)
{
if(!finalVerts.Contains(point))
finalVerts.Add(point);
}
}
return finalVerts.ToArray();
}
}
Untested ideas:
See if the triangles are always defined in pairs. If so, you can get the four points by processing each triangle pair.
Another idea. The middle of each quad will be the midpoint of the longest side of each triangle. Find the midpoint of each triangle and then remove duplicates.
Good ideas, though I just found out that GetTriangles() doesn't actually return the vertices of the triangles so it's still an issue.
It returns the index into the $$anonymous$$esh.vertices array, so it is just one indirection. So you will have something like:
var vertices = mesh.vertices;
var triangles = mesh.triangles;
/...
var vertex = vertices[triangles[someIndex]];
It is more efficient to find the middle point and then convert it to world space rather than to convert all the vertices to world coordinates. Plus you will have to assume some sort of order of the vertices in order to use just the vertices to find the middle of each quad.