Problem with layer mask and nodes
I'm following this tutorial about pathfinding: https://www.youtube.com/watch?v=nhiFx28e7JY&list=PLFt_AvWsXl0cq5Umv3pMC9SPnKjfp9eGW∈dex=2
I've followed all the steps but, when it's time to run the game, this happens:
As you can see, all the blocks are white. But they should turn red if one of the objects (the red square on the top left) is in the "Unwalkable" layer.
I've uploaded the code that I'm using for this.
If anyone can point out what's wrong, that'll be appreciated.
Answer by Inryhk · Aug 19, 2019 at 08:03 PM
Well, don't know if you are still interested, but after long time of debugging I solved it. If you are using 2D and OverlapCircle, your object transform position is not actually moving so the Circle is drawn in the middle of the map. That is why all of them are white, if you put something in the middle it will all be red. So my solution to Your problem is:
bool walkable = !(Physics2D.OverlapCircle((Vector2)worldPoint, 0.1f, unwalkable));
That is entire working script for 2d from this video:
public class Grid : $$anonymous$$onoBehaviour
{
public Layer$$anonymous$$ask unwalkable;
public Vector2 gridWorldSize;
public float nodeRadius;
Node[,] grid;
float nodeDiameter;
int gridSizeX, gridSizeY;
void Start()
{
nodeDiameter = nodeRadius*2;
gridSizeX = $$anonymous$$athf.RoundToInt(gridWorldSize.x / nodeDiameter);
gridSizeY = $$anonymous$$athf.RoundToInt(gridWorldSize.y / nodeDiameter);
Debug.Log("gridSizeX is " + gridSizeX);
Debug.Log("gridSizeY is " + gridSizeY);
CreateGrid();
}
void CreateGrid()
{
grid = new Node[gridSizeX, gridSizeY];
Vector2 worldBottomLeft = (Vector2)transform.position - Vector2.right * gridWorldSize.x / 2 - Vector2.up * gridWorldSize.y / 2;
Debug.Log("worldBottomLeft is " + worldBottomLeft);
for (int x = 0; x < gridSizeX; x++)
{
for (int y = 0; y < gridSizeY; y++)
{
Vector2 worldPoint = worldBottomLeft + Vector2.right * (x * nodeDiameter + nodeRadius) + Vector2.up * (y * nodeDiameter + nodeRadius);
Debug.Log("worldPoint is " + worldPoint);
bool walkable = !(Physics2D.OverlapCircle((Vector2)worldPoint, 0.1f, unwalkable));
Debug.Log("worldPoint is " + worldPoint);
grid[x, y] = new Node(walkable, worldPoint);
}
}
}
public void OnDrawGizmos()
{
Gizmos.DrawWireCube(transform.position, new Vector2(gridWorldSize.x, gridWorldSize.y));
if (grid != null)
{
foreach (Node n in grid)
{
Gizmos.color = (n.walkable) ? Color.white : Color.red;
Gizmos.DrawCube(n.worldPosition, Vector2.one * (nodeDiameter - 0.01f));
}
}
}
Your answer
Follow this Question
Related Questions
InvalidOperationException thrown 0 Answers
Can't change an object Layers at runtime via c# code (Help Please) 0 Answers
come implemento il touch con il void mouseover? 0 Answers
What is the most effective way to structure Card Effects in a Single Player game? 1 Answer
Adjust the size of the object within a parent container 0 Answers