Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Nadav-Ruskin/15c09f9c03eee30cfcfa4eb3cb08580a to your computer and use it in GitHub Desktop.
Save Nadav-Ruskin/15c09f9c03eee30cfcfa4eb3cb08580a to your computer and use it in GitHub Desktop.
Create a navigation region for a NavigationRegion2D from a NavigationRegion2D
extends Node2D
@onready var collision_shape_2d: CollisionShape2D = $Area2D/CollisionShape2D
@onready var navigation_region_2d: NavigationRegion2D = $NavigationRegion2D
func _ready() -> void:
"""
When object is ready, bake a navigation mesh from its collision shape.
"""
var rect: Rect2 = collision_shape_2d.shape.get_rect()
var a = rect.position + collision_shape_2d.position
var b = Vector2(rect.position.x + rect.size.x, rect.position.y) + collision_shape_2d.position
var c = Vector2(rect.position.x, rect.position.y + rect.size.y) + collision_shape_2d.position
var d = rect.end + collision_shape_2d.position
var new_navigation_mesh = NavigationPolygon.new()
new_navigation_mesh.agent_radius = 0
var bounding_outline = PackedVector2Array([a, b, d, c])
#var bounding_outline = PackedVector2Array([Vector2(0, 0), Vector2(0, 50), Vector2(50, 50), Vector2(50, 0)])
new_navigation_mesh.add_outline(bounding_outline)
NavigationServer2D.bake_from_source_geometry_data(new_navigation_mesh, NavigationMeshSourceGeometryData2D.new());
navigation_region_2d.navigation_polygon = new_navigation_mesh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment