Reputation: 21
I'm currently developing a game in Godot 4.0, and I've come across a challenge I'm unable to solve.
In my game, the level design is dynamic and involves placing walls and other terrain pieces at runtime. I would like to have the navigation mesh automatically updated to account for these new walls as soon as they are placed. However, I'm having difficulty achieving this.
I've tried adding a NavigationRegion2D to the Main Scene. The walls scenes are instantiated by the Main Scene script:
// For Debugging
public Vector2[] D_vertices = new Vector2[4 + 24 * 4];
public void SpawnWalls(Wall[] walls, NavigationRegion2D NavRegion)
{
var polygon = new NavigationPolygon();
var screenOutline = new Vector2[] { new Vector2(10, 10),
new Vector2(10, 590),
new Vector2(790, 590),
new Vector2(790, 10) };
// polygon.AddOutline(screenOutline);
// polygon.MakePolygonsFromOutlines();
Vector2[] vertices = new Vector2[4 + walls.Length * 4];
vertices[0] = screenOutline[0];
vertices[1] = screenOutline[1];
vertices[2] = screenOutline[2];
vertices[3] = screenOutline[3];
for (int i = 1; i < walls.Length; i++)
{
walls[i] = WallScene.Instantiate<Wall>();
Vector2 TempPosition = new Vector2(32 + 16 + 32 * i, 200);
walls[i].Position = TempPosition;
AddChild(walls[i]);
vertices[i*4 + 0] = TempPosition + new Vector2(-16, -16);
vertices[i*4 + 1] = TempPosition + new Vector2(-16, 16);
vertices[i*4 + 2] = TempPosition + new Vector2(16, 16);
vertices[i*4 + 3] = TempPosition + new Vector2(16, -16);
}
// polygon.AddPolygon()
// Visualize NavigationMesh on Screen
D_vertices = vertices;
polygon.Vertices = vertices;
var indices = new int[] { 0, 1, 2, 3};
polygon.AddPolygon(indices);
NavRegion.NavigationPolygon = polygon;
}
I expected this code to generate a 4 sided polygon slightly smaller than the size of the game window, and then for each Wall added, generate a polygon hole in the larger polygon. The hole would be an area in which entities could not navigate through.
I have used NavigationAgent2D nodes in the Godot scenes of entities that are meant to be navigating the level. I expect the entities to navigate around the Walls. However, in the code provided above the entities just ignore the Walls.
I feel this could be an issue with the polygons I am generating, but I do not know how to fix it.
Below is an image of what the polygons look like when the game is run.
The red lines connect all the vertices of the NavigationPolygon inside NavigationRegion2D.
Upvotes: 1
Views: 890