Unity astar 寻路项目——如何从网格中随机选择一个位置?

Unity astar pathfinding project - how to pick a random position from the grid?

我最近买了一个starpathfinding project pro。 我正在制作敌人 ai,我希望它在找到目标之前随机移动。 我的项目是二维的。 我如何在网格上选择一个随机位置? 如果可以的话,你能给我举个例子吗?

不太确定您购买的插件,但如果您使用的是瓷砖地图,您可以迭代网格中每个瓷砖地图中的每个瓷砖(仅在关卡加载时一次)并生成随机数的 x 和 y从中选择一个有效的图块位置并使用 A* 算法使 Ai 移动到那里。

编辑:这可能不是最好的写法,但这是我过去对它们进行迭代的方式,如果需要,您可以根据未来的需要添加或更改其中的内容。

using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Tilemaps;
 public class TileMapCollision : MonoBehaviour
{
    [SerializeField] private GameObject gridObject;
    private TileBase tile;
    public List<Vector3> StoredStaticSolidTilePositions;
    private void Awake()
    {
        TileSearch();
    }

    private void TileSearch()
    {
        List<Tilemap> tilemaps = gridObject.GetComponentsInChildren<Tilemap>().ToList();
        foreach (Tilemap tilemap in tilemaps)
        {
            tilemap.CompressBounds();
            BoundsInt TilemapBounds = tilemap.cellBounds;
            for (int x = TilemapBounds.xMin; x < TilemapBounds.xMax; x++)
            {
                for (int y = TilemapBounds.yMin; y < TilemapBounds.yMax; y++)
                {
                    Vector3Int localPos = new Vector3Int(x,y, (int)tilemap.transform.position.z);
                    Vector3 worldPos = tilemap.CellToWorld(localPos);
                    if (tilemap.HasTile(localPos))
                    {
                        if (tilemap.CompareTag("Solid"))
                        {
                            StoredStaticSolidTilePositions.Add(worldPos);
                        }
                    }
                }
            }
        }
    }
}

我不知道您使用的是什么工具,也不知道您的“网格”到底是什么样子,但从评论来看,您似乎有一个 TileMap

一般来说,从一个值中挑选一个随机数有 Random.Range。 (请注意,第二个(上)参数是 exclusive for int。)

然后你可以获得TileMap.size并简单地从TileMap的维度

内的三个随机索引生成一个位置
var gridSize = tilemap.size;
var randomPos = new Vector3Int(Random.Range(0, gridSize.x), Random.Range(0, gridSize.y), Random.Range(0, gridSize.z));
var randomTile = tilemap.GetTile(randomPos);