Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class NavGrid : MonoBehaviour {
- public Vector2 size;
- public float nodeSize = 1;
- public LayerMask collisionMask;
- public float height = 10;
- public Transform test;
- Node[,] debugNodes;
- [ContextMenu("Gen nodes")]
- public Node[,] GenerateNodes()
- {
- Vector2Int numNodes = NumNodes;
- Node[,] nodes = new Node[numNodes.x,numNodes.y];
- // Vector3 rayTopLeft = new Vector3(-nodeSize * numNodes.x / 2f, height, nodeSize * numNodes.y / 2f);
- for (int y = 0; y < numNodes.y; y++)
- {
- for (int x = 0; x < numNodes.x; x++)
- {
- Vector3 rayPos = WorldPosCentreOfCoordinate(x, y) + Vector3.up * height;
- RaycastHit hit;
- Vector3 nodePosition = new Vector3(rayPos.x, 0, rayPos.z);
- bool nodeIsTraversable = false;
- if (Physics.Raycast(rayPos, Vector3.down, out hit, height * 2, collisionMask))
- {
- nodePosition = hit.point;
- if (hit.collider.tag == "Ground")
- {
- nodeIsTraversable = true;
- }
- }
- nodes[x, y] = new Node(nodeIsTraversable, nodePosition, new Vector2Int(x,y));
- }
- }
- debugNodes = nodes;
- return nodes;
- }
- public Vector3 WorldPosCentreOfCoordinate(int x, int y)
- {
- Vector3 topLeft = new Vector3(-nodeSize * (NumNodes.x-1) / 2f,0, nodeSize * (NumNodes.y-1) / 2f);
- return topLeft + (Vector3.right * x + Vector3.back * y) * nodeSize;
- }
- public Vector2Int CoordinateFromWorldPos(Vector3 pos)
- {
- int x = Mathf.RoundToInt((pos.x) / nodeSize + (NumNodes.x - 1) * .5f);
- int y = Mathf.RoundToInt((-pos.z) / nodeSize + (NumNodes.y - 1) * .5f);
- return new Vector2Int(Mathf.Clamp(x, 0, NumNodes.x - 1), Mathf.Clamp(y, 0, NumNodes.y - 1));
- }
- Vector2Int NumNodes
- {
- get
- {
- return new Vector2Int(Mathf.RoundToInt(size.x / nodeSize), Mathf.RoundToInt(size.y / nodeSize));
- }
- }
- private void OnDrawGizmos()
- {
- Vector2Int coordFromWorldTest = CoordinateFromWorldPos(test.position);
- for (int y = 0; y < NumNodes.y; y++)
- {
- for (int x = 0; x < NumNodes.x; x++)
- {
- if (x == coordFromWorldTest.x && y == coordFromWorldTest.y)
- {
- Gizmos.DrawCube(WorldPosCentreOfCoordinate(x, y) + Vector3.up * height, new Vector3(nodeSize, 0, nodeSize));
- }
- else
- {
- Gizmos.DrawWireCube(WorldPosCentreOfCoordinate(x, y) + Vector3.up * height, new Vector3(nodeSize, 0, nodeSize));
- if (debugNodes != null)
- {
- if (!debugNodes[x, y].isTraversable)
- {
- Gizmos.color = new Color(1, 0, 0, .5f);
- Gizmos.DrawCube(WorldPosCentreOfCoordinate(x, y) + Vector3.up * height, new Vector3(nodeSize, 0, nodeSize));
- Gizmos.color = Color.white;
- }
- }
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment