示例#1
0
    private PathfindingGrid BuildGrid()
    {
        float nodeDiam = nodeRadius * 2f;
        int   width    = Mathf.CeilToInt(gridSize.x / nodeDiam);
        int   height   = Mathf.CeilToInt(gridSize.y / nodeDiam);

        PathfindingGrid grid = new PathfindingGrid();

        grid.width    = width;
        grid.height   = height;
        grid.grid     = new Unity.Collections.NativeArray <Node>(width * height, Unity.Collections.Allocator.Persistent);
        grid.nodeSize = nodeDiam;

        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                var rayOrigin = grid.GetNodePosition(x, y);
                rayOrigin.y = gridHeight;
                var rayDir = Vector3.down;
                var ray    = new Ray(rayOrigin, rayDir);

                if (Physics.Raycast(ray, out RaycastHit hit, gridHeight))
                {
                    bool obstructed = CheckCube(hit.point, nodeRadius);
                    Node node       = new Node()
                    {
                        yPosition = hit.point.y,
                        walkable  = !obstructed && (walkable == (walkable | (1 << hit.collider.gameObject.layer)))
                    };

                    grid.grid[y * width + x] = node;
                }