Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

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

I bought astarpathfinding project pro recently. I am making enemy ai and I want it to move randomly before it finds its target. My project is in 2d. How do I pick a random position on the grid? if you can, can you show me some example of it?

question from:https://stackoverflow.com/questions/65877948/unity-astar-pathfinding-project-how-to-pick-a-random-position-from-the-grid

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Not really sure about the plugin that you bought, but If you are using tilemaps, you could iterate over every tile in each tilemap in your grid(only once on level loading) and generate a random number of x and y to choose a valid tile position from and make the Ai move there using the A* algorithm.

Edit: May not be the best way to write this, but this is how I iterated over them in the past, you can add or change things in it for your future needs if you want.

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);
                        }
                    }
                }
            }
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...