I am working on 2D game, My 2D project need use pathfinding. I search manual from official, and I found the NavMesh Pathfinding of unity support 3D game only… there must be mesh renderer. It cant work on 2D because there is no mesh renderer, unless you add MeshRenderer component add to GameObject,But it conflict with 2D SpriteRenderer…
So… I use the vertex coordinates of Collider2D attached to gameobject to create mesh, eg:
private MeshTransform CreateEdge2dMesh (EdgeCollider2D e2d)
{
if (e2d == null) {
return null;
}
Vector2[] points = e2d.points;
Vector2 offset = e2d.offset;
Bounds bounds = e2d.bounds;
Vector3 cv = new Vector3 (bounds.center.x, bounds.center.y, 0);
Vector3[] vertices = new Vector3[points.Length + 1];
Vector2[] uvs = new Vector2[vertices.Length];
int[] triangles = new int[(points.Length - 1) * TRIANGLES_COUNT];
vertices [points.Length] = cv;
uvs [points.Length] = Vector2.zero;
for (int i = 0; i < points.Length; i++) {
Vector2 pt = e2d.transform.TransformPoint (points [i]);
vertices [i] = new Vector3 (pt.x + offset.x, pt.y + offset.y, 0);
uvs [i] = Vector2.zero;
if (i < points.Length - 1) {
triangles [i * TRIANGLES_COUNT] = i;
triangles [(i * TRIANGLES_COUNT) + 1] = i + 1;
triangles [(i * TRIANGLES_COUNT) + 2] = points.Length;
}
}
Mesh mesh = new Mesh ();
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.uv = uvs;
mesh.RecalculateNormals ();
MeshTransform mt = new MeshTransform ();
mt.mesh = mesh;
mt.transform = e2d.transform;
return mt;
}
Then I call the function eg:
public void AddMesh (MeshTransform mt)
{
if (mt == null) {
return;
}
NavMeshBuildSource nmbs = new NavMeshBuildSource ();
nmbs.shape = NavMeshBuildSourceShape.Mesh;
nmbs.transform = mt.transform.localToWorldMatrix;
nmbs.area = 0;
nmbs.sourceObject = mt.mesh;
m_NavMeshSourceList.Add (nmbs);
}
and call NavMeshBuilder.UpdateNavMeshData…
I add the NavMeshAgent to my player, but it doesn’t work.
Console print:
Failed to create agent because it is not close enough to the NavMesh
I think the NavMesh PathFinding system need the mesh vertex information to create or bake the walkable/diswalkable area, I create mesh which sharp is exactly match the collider, and use this to create/bake walkable area…
Do I went about it in the wrong way?..
thx…