Агент никогда не движется по пути поверхности Навимеша при выпечке в сценарии. Как заставить агент двигаться по пути, а C#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 Агент никогда не движется по пути поверхности Навимеша при выпечке в сценарии. Как заставить агент двигаться по пути, а

Сообщение Anonymous »

Это когда агент начинает двигаться во время перемещения, начинающегося в положении 1,1,1 на пути лабиринта, а затем он перемещается по диагонали в положение назначения. Это не работает, агент всегда движется по диагонали, игнорируя стены, а не на пути. Запеченный путь ". src = "https://i.sstatic.net/a2566kw8.jpg"/>
Это показывают настройки генератора лабиринта в инспекторе, включая скрипт и поверхность. src = "https://i.sstatic.net/2fuypuzm.jpg"/>
и сценарий, который прикреплен к генератору лабиринга. void Start()
{
// Ensure odd dimensions
if (width % 2 == 0) width++;
if (height % 2 == 0) height++;

maze = new bool[width, height];
GenerateMaze();
DrawMaze();

GetComponent().BuildNavMesh();

// Instantiate agent at entrance and set destination to exit
Vector3 startPos = new Vector3(1, 0, 1); // Entrance at (1,1)
Vector3 goalPos = new Vector3(width - 2, 0, height - 2); // Exit at (width-2, height-2)
GameObject agent = Instantiate(agentPrefab, startPos, Quaternion.identity);

NavMeshAgent nav = agent.GetComponent();
if (nav != null)
{
//nav.Warp(startPos); // Optional: warp agent to the exact position
nav.destination = goalPos;
}
}
< /code>
Полный скрипт: в методе Drawmaze я попробовал после того, как он не работал хорошо, чтобы установить стены статическим, но он также не решил, что агент движется. < /p>
using System.Collections.Generic;
using Unity.AI.Navigation;
using UnityEngine;
using UnityEngine.AI;

public class MazeGenerator : MonoBehaviour
{
[Header("Maze Settings")]
public int width = 21;
public int height = 11;
public GameObject wallPrefab;
public Transform mazeParent;
public GameObject agentPrefab;

private bool[,] maze;

void Start()
{
// Ensure odd dimensions
if (width % 2 == 0) width++;
if (height % 2 == 0) height++;

maze = new bool[width, height];
GenerateMaze();
DrawMaze();

GetComponent().BuildNavMesh();

// Instantiate agent at entrance and set destination to exit
Vector3 startPos = new Vector3(1, 0, 1); // Entrance at (1,1)
Vector3 goalPos = new Vector3(width - 2, 0, height - 2); // Exit at (width-2, height-2)
GameObject agent = Instantiate(agentPrefab, startPos, Quaternion.identity);

NavMeshAgent nav = agent.GetComponent();
if (nav != null)
{
//nav.Warp(startPos); // Optional: warp agent to the exact position
nav.destination = goalPos;
}
}

void GenerateMaze()
{
// Initialize all cells as walls
for (int x = 0; x < width; x++)
for (int y = 0; y < height; y++)
maze[x, y] = true;

Vector2Int start = new Vector2Int(1, 1);
maze[start.x, start.y] = false;

Stack stack = new Stack();
stack.Push(start);

Vector2Int[] dirs = new Vector2Int[]
{
new Vector2Int(0, 2),
new Vector2Int(0, -2),
new Vector2Int(2, 0),
new Vector2Int(-2, 0)
};

while (stack.Count > 0)
{
Vector2Int current = stack.Pop();
Shuffle(dirs);

foreach (var dir in dirs)
{
Vector2Int neighbor = current + dir;
if (IsInBounds(neighbor) && maze[neighbor.x, neighbor.y])
{
maze[neighbor.x, neighbor.y] = false;
Vector2Int between = current + dir / 2;
maze[between.x, between.y] = false;
stack.Push(neighbor);
}
}
}
}

void DrawMaze()
{
if (mazeParent == null)
mazeParent = new GameObject("Maze Cells").transform;

for (int x = -1; x = 0 && y < height && maze[x, y]);

if (isWall)
{
Vector3 pos = new Vector3(x, 0, y);
GameObject wall = Instantiate(wallPrefab, pos, Quaternion.identity, mazeParent);
wall.name = $"Wall {x}.{y}";
//wall.isStatic = true; // Required for NavMesh
}
}
}
}

bool IsInBounds(Vector2Int pos)
{
return pos.x > 0 && pos.x < width - 1 && pos.y > 0 && pos.y < height - 1;
}

void Shuffle(Vector2Int[] array)
{
for (int i = 0; i < array.Length; i++)
{
int rand = Random.Range(i, array.Length);
Vector2Int temp = array;
array = array[rand];
array[rand] = temp;
}
}
}


Подробнее здесь: https://stackoverflow.com/questions/797 ... ript-how-t
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C#»