-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNodeGrid.cs
More file actions
105 lines (98 loc) · 3.8 KB
/
NodeGrid.cs
File metadata and controls
105 lines (98 loc) · 3.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
namespace TilePathFinder
{
public class NodeGrid
{
public NodeGrid(Grid _TileGrid, string _wallTag, string _FloorTag)
{
tileGrid = _TileGrid;
wallTag = _wallTag;
floorTag = _FloorTag;
if (tileGrid != null && wallTag != "")
CreateGrid();
}
public Grid tileGrid;
public string wallTag = "Blocking";
public string floorTag = "Floor";
public Vector2Int vGridWorldSize;
public Node[,] nodeArray;
public int xOffset;
public int yOffset;
public void CreateGrid()
{
// Get all tilemaps
Tilemap[] allTileMaps = tileGrid.GetComponentsInChildren<Tilemap>();
// Check for largest tilemap
int largestX = 0, largestY = 0;
foreach (Tilemap map in allTileMaps)
{
map.CompressBounds();
BoundsInt bounds = map.cellBounds;
if (bounds.size.x > largestX)
largestX = map.size.x;
if (bounds.size.y > largestY)
largestY = map.size.y;
if (map.cellBounds.xMin < xOffset)
xOffset = map.cellBounds.xMin;
if (map.cellBounds.yMin < yOffset)
yOffset = map.cellBounds.yMin;
}
// Setup variables
nodeArray = new Node[largestX, largestY];
vGridWorldSize.x = largestX;
xOffset = xOffset * -1;
yOffset = yOffset * -1;
vGridWorldSize.y = largestY;
// Add nodes
foreach (Tilemap map in allTileMaps)
{
foreach (var pos in map.cellBounds.allPositionsWithin)
{
int gridPosX = pos.x + xOffset;
int gridPosY = pos.y + yOffset;
// Make new node
if (nodeArray[gridPosX, gridPosY] == null)
{
// Check tag
if (map.tag == wallTag)
{
nodeArray[gridPosX, gridPosY] = new Node(gridPosX, gridPosY, false);
}
else if (map.tag == floorTag && map.GetTile(new Vector3Int(pos.x, pos.y, 0)) != null)
{
nodeArray[gridPosX, gridPosY] = new Node(gridPosX, gridPosY, true);
}
}
// Check existing node
else if (map.tag == wallTag || nodeArray[gridPosX, gridPosY].walkable == false || map.tag != floorTag)
{
nodeArray[gridPosX, gridPosY].walkable = false;
}
}
}
}
public List<Node> GetNeighbours(Node node)
{
List<Node> neighbours = new List<Node>();
for (int x = -1; x <= 1; x++)
{
for (int y = -1; y <= 1; y++)
{
if (x == 0 && y == 0)
continue;
int checkX = node.gridX + x;
int checkY = node.gridY + y;
if (checkX >= 0 && checkX < vGridWorldSize.x && checkY >= 0 && checkY < vGridWorldSize.y)
{
if (nodeArray[checkX, checkY] != null && nodeArray[checkX, checkY].walkable)
neighbours.Add(nodeArray[checkX, checkY]);
}
}
}
return neighbours;
}
}
}