Advertisement
SebastianLague

A* Pathfinding Tutorial 02

Dec 18th, 2014
4,704
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.91 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Grid : MonoBehaviour {
  5.  
  6.     public LayerMask unwalkableMask;
  7.     public Vector2 gridWorldSize;
  8.     public float nodeRadius;
  9.     Node[,] grid;
  10.  
  11.     float nodeDiameter;
  12.     int gridSizeX, gridSizeY;
  13.  
  14.     void Start() {
  15.         nodeDiameter = nodeRadius*2;
  16.         gridSizeX = Mathf.RoundToInt(gridWorldSize.x/nodeDiameter);
  17.         gridSizeY = Mathf.RoundToInt(gridWorldSize.y/nodeDiameter);
  18.         CreateGrid();
  19.     }
  20.  
  21.     void CreateGrid() {
  22.         grid = new Node[gridSizeX,gridSizeY];
  23.         Vector3 worldBottomLeft = transform.position - Vector3.right * gridWorldSize.x/2 - Vector3.forward*     gridWorldSize.y/2;
  24.  
  25.         for (int x = 0; x < gridSizeX; x ++) {
  26.             for (int y = 0; y < gridSizeY; y ++) {
  27.                 Vector3 worldPoint = worldBottomLeft + Vector3.right * (x * nodeDiameter + nodeRadius) + Vector3.forward * (y * nodeDiameter + nodeRadius);
  28.                 bool walkable = !(Physics.CheckSphere(worldPoint,nodeRadius,unwalkableMask));
  29.                 grid[x,y] = new Node(walkable,worldPoint);
  30.             }
  31.         }
  32.     }
  33.  
  34.     public Node NodeFromWorldPoint(Vector3 worldPosition) {
  35.         float percentX = (worldPosition.x + gridWorldSize.x/2) / gridWorldSize.x;
  36.         float percentY = (worldPosition.z + gridWorldSize.y/2) / gridWorldSize.y;
  37.         percentX = Mathf.Clamp01(percentX);
  38.         percentY = Mathf.Clamp01(percentY);
  39.  
  40.         int x = Mathf.RoundToInt((gridSizeX-1) * percentX);
  41.         int y = Mathf.RoundToInt((gridSizeY-1) * percentY);
  42.         return grid[x,y];
  43.     }
  44.  
  45.     void OnDrawGizmos() {
  46.         Gizmos.DrawWireCube(transform.position,new Vector3(gridWorldSize.x,1,gridWorldSize.y));
  47.  
  48.         if (grid != null) {
  49.             foreach (Node n in grid) {
  50.                 Gizmos.color = (n.walkable)?Color.white:Color.red;
  51.                 Gizmos.DrawCube(n.worldPosition, Vector3.one * (nodeDiameter-.1f));
  52.             }
  53.         }
  54.     }
  55. }
  56.  
  57. public class Node {
  58.    
  59.     public bool walkable;
  60.     public Vector3 worldPosition;
  61.    
  62.     public Node(bool _walkable, Vector3 _worldPos) {
  63.         walkable = _walkable;
  64.         worldPosition = _worldPos;
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement