Obstacles in pathfinding do not work

Godot Version

Godot 4.2.2


Pathfinding obstacles don’t work,player passes through obstacles, my scene looks like this:

The code I use is this:

extends CharacterBody2D

var movement_speed: float = 200.0
var movement_target_position: Vector2 = Vector2(60.0,180.0)

@onready var navigation_agent: NavigationAgent2D = $NavigationAgent2D

func _ready():
	navigation_agent.path_desired_distance = 4.0
	navigation_agent.target_desired_distance = 4.0

func set_movement_target(movement_target: Vector2):
	navigation_agent.target_position = movement_target

func _physics_process(delta):
	#if navigation_agent.is_navigation_finished():
	#	return

	var current_agent_position: Vector2 = global_position
	var next_path_position: Vector2 = navigation_agent.get_next_path_position()

	velocity = current_agent_position.direction_to(next_path_position) * movement_speed
func  _process(delta: float) -> void:
	movement_target_position = get_global_mouse_position()

Is your obstacle on layer 1? You have set up your navigation to only consider layer 1, which is typically the player and not the obstacle?

yes, all layers are set to 1 by default

I made the obstacle physical using StaticBody2D, but it just slides over it instead of going around it =(

Looks like you haven’t turned on avoidance, you also need to use the dedicated methods and signals to use avoidance, see here

NavigationObstacle in Godot 4.2 is for avoidance only, it does nothing for pathfinding.

You need to remove the navigation mesh below the obstacle if you do not want paths to go through it.

1 Like

I need to get around this obstacle, how can I do this? my code written above does not work with Navigation Obstacle 2D, it just rests on it and that’s it

additional question, can NavigationObstacle2D somehow take the shape of a sprite, or is it just a point with a center?

For the pathfinding you (re)bake the navigation mesh so that the shape of your obstacle is not included in the navigation mesh surface. If you are on Godot 4.3dev6 or later the obstacle node has a new property “affect_navigation_mesh” so that is included in a navigation mesh baking process like any other static geometry. On older Godot versions without that property just add e.g. a physics staticbody with a shape like the obstacle and set it to a collision layer that gets only parsed by the navigation mesh baking.

Navigation obstacles have two modes, dynamic and static. If you want to define a “shape” you use the static variant which means you define the vertices outline. See obstacle documentation for details here Using NavigationObstacles — Godot Engine (latest) documentation in English


If you have time, could you make a minimal example with NavigationObstacle2D?
I will be very grateful!