PathfindingVisual.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. ------------------- Code Monkey -------------------
  3. Thank you for downloading this package
  4. I hope you find it useful in your projects
  5. If you have any questions let me know
  6. Cheers!
  7. unitycodemonkey.com
  8. --------------------------------------------------
  9. */
  10. using System.Collections;
  11. using System.Collections.Generic;
  12. using UnityEngine;
  13. public class PathfindingVisual : MonoBehaviour {
  14. private GridXZ<PathNode> grid;
  15. private Mesh mesh;
  16. private bool updateMesh;
  17. private void Awake() {
  18. mesh = new Mesh();
  19. GetComponent<MeshFilter>().mesh = mesh;
  20. }
  21. public void SetGrid(GridXZ<PathNode> grid) {
  22. this.grid = grid;
  23. UpdateVisual();
  24. grid.OnGridObjectChanged += Grid_OnGridValueChanged;
  25. }
  26. private void Grid_OnGridValueChanged(object sender, GridXZ<PathNode>.OnGridObjectChangedEventArgs e) {
  27. updateMesh = true;
  28. }
  29. private void LateUpdate() {
  30. if (updateMesh) {
  31. updateMesh = false;
  32. UpdateVisual();
  33. }
  34. }
  35. private void UpdateVisual() {
  36. MeshUtils.CreateEmptyMeshArrays(grid.GetWidth() * grid.GetHeight(), out Vector3[] vertices, out Vector2[] uv, out int[] triangles);
  37. for (int x = 0; x < grid.GetWidth(); x++) {
  38. for (int z = 0; z < grid.GetHeight(); z++) {
  39. int index = x * grid.GetHeight() + z;
  40. Vector3 quadSize = new Vector3(1, 0, 1) * grid.GetCellSize();
  41. PathNode pathNode = grid.GetGridObject(x, z);
  42. if (pathNode.isWalkable) {
  43. quadSize = Vector3.zero;
  44. }
  45. MeshUtils.AddToMeshArraysXZ(vertices, uv, triangles, index, grid.GetWorldPosition(x, z) + quadSize * .5f, 0f, quadSize, Vector2.zero, Vector2.zero);
  46. }
  47. }
  48. mesh.vertices = vertices;
  49. mesh.uv = uv;
  50. mesh.triangles = triangles;
  51. }
  52. }