Hey,
I’m having an issue with making an A* grid that is using a polygoncollider2d as the map bounds and then using the boxcast to determine if A collider was hit, however the boxcast is always returning true:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AStarGrid : MonoBehaviour
{
public LayerMask layerMask;
public PolygonCollider2D unwalkableCollider;
public Vector2 gridWorldSize;
public float nodeRadius;
Node[,] grid;
float nodeDiameter;
uint gridSizeX, gridSizeY;
public void Start()
{
nodeDiameter = nodeRadius * 2;
gridSizeX = (uint)(gridWorldSize.x / nodeDiameter);
gridSizeY = (uint)(gridWorldSize.y / nodeDiameter);
Debug.Log("Gridsize = : " + gridSizeX + "," + gridSizeY);
CreateGrid();
}
private void CreateGrid()
{
grid = new Node[gridSizeX, gridSizeY];
bool isWalkable = true;
Vector3 worldBottomLeft = transform.position - Vector3.right * gridWorldSize.x / 2 - Vector3.up * gridWorldSize.y / 2;
for (int i = 0; i < gridSizeX; i++)
{
for (int j = 0; j < gridSizeY; j++)
{
Vector3 worldPoint = worldBottomLeft + Vector3.right * (i * nodeDiameter + nodeRadius) + Vector3.up * (j * nodeDiameter + nodeRadius);
/*
RaycastHit2D hit = (Physics2D.BoxCast(new Vector2(worldPoint.x - nodeRadius, worldPoint.y - nodeRadius), new Vector2(nodeDiameter, nodeDiameter), 0.0f, Vector2.right))
if (hit.collider != null)
{
Debug.Log("Hit Collider: " + hit.collider.name);
if (hit.collider == unwalkableCollider)
{
isWalkable = false;
}
}
*/
Collider2D[] colls = Physics2D.OverlapBoxAll(new Vector2(worldPoint.x - nodeRadius, worldPoint.y - nodeRadius), new Vector2(nodeDiameter, nodeDiameter), 0.0f);
foreach (Collider2D coll in colls)
{
if (coll == unwalkableCollider)
isWalkable = false;
}
grid[i, j] = new Node(isWalkable, worldPoint);
}
}
}
private void OnDrawGizmos()
{
Gizmos.DrawWireCube(transform.position, new Vector3(gridWorldSize.x, gridWorldSize.y, 1));
if (grid != null)
{
foreach (Node node in grid)
{
Gizmos.color = (node.isWalkable) ? Color.white : Color.red;
Gizmos.DrawCube(node.worldPosition, Vector3.one * (nodeDiameter - .1f));
}
}
}
}
The node class simply holds whether it’s walkable and it’s position.
however when the code is run all node returned are red (and thus determined to have collided with the polygon 2D, even nodes that are spawned over the edge of the sprite holding the collider)
I was wondering if anyone could tell me what I’m doing wrong / how they’ve done it in the past,
Thank you