When I click on close points, the character moves, but when I click on far points, the game freezes and the program does not respond. Or I made a mistake while setting navigationRegion2D.
extends CharacterBody2D
@export var speed = 50
@onready var nav: NavigationAgent2D = $Navigation/NavigationAgent2D
var target = null
var homePos = Vector2.ZERO
func _ready():
homePos = global_position
nav.path_desired_distance = 4
nav.target_desired_distance = 4
func _physics_process(delta):
recalc_path()
if nav.is_navigation_finished():
homePos = global_position
return
var axis = to_local(nav.get_next_path_position()).normalized()
velocity = axis * speed
move_and_slide()
if axis.x < 0:
$Sprite2D.flip_h = false
else:
$Sprite2D.flip_h = true
func recalc_path():
if target:
nav.target_position = target
else:
nav.target_position = homePos
func _input(event):
if Input.is_action_just_pressed(“left_click”):
target = get_global_mouse_position()