Nav Agent tanks my fps

Godot Version


const speed = 400

@onready var enemy = $EnemySprite
@onready var raycast = $EnemyRayCast

@onready var nav_agent = $EnemyNavigation as NavigationAgent2D

func _ready() -> void:
	makepath()

func _process(delta: float) -> void:
	if raycast.get_collider() is TileMap:
		var atlas_coord = raycast.get_collider().get_coords_for_body_rid(raycast.get_collider_rid())
		var tile_data = raycast.get_collider().get_cell_tile_data(0,atlas_coord) 
		var custom_data_getter = tile_data.get_custom_data("collision")
		if custom_data_getter == true:
			queue_free()


func _physics_process(delta: float) -> void:
	var player = get_tree().get_nodes_in_group("world")[0]
	
	move()
	
	if player.position.x < global_position.x:
		enemy.flip_h = true
	else:
		enemy.flip_h = false
	
	move_and_slide()

func makepath() -> void:
	var player = get_tree().get_nodes_in_group("world")[0]
	nav_agent.target_position = player.global_position
	

func move():
	var direction = to_local(nav_agent.get_next_path_position()).normalized()
	velocity = direction * speed
	enemy.play()
		
func _on_area_2d_body_entered(body: Node2D) -> void:
	if body.is_in_group("player"):
		get_node("/root/Global").score = 0
		get_tree().change_scene_to_file("res://Scenes/main_menu.tscn")


func _on_area_2d_area_entered(area: Area2D) -> void:
	if area.is_in_group("Bullets"):
		queue_free()


func _on_timer_timeout() -> void:
	makepath()


func _on_visible_on_screen_notifier_2d_screen_exited() -> void:
	queue_free()

Question

I use nav agent to pathfind path to player and it tanks my fps

This is not going to help. 60 times a second you are getting all the nodes in the tree just to get the first one (which I presume is the player). Just assign it to a reference something like:

var player

func _ready():
    player = get_tree().get_nodes_in_group("world")[0]

I say something like this because I don’t know if all your nodes will be ready by the time this _ready function is called, you might need to assign the reference Player later or inject it from your root node when everything else is ready, or call an initialisation function from your root etc.

1 Like

didnt work

Certainly some code-smells as paul pointed out, have you check the profiler to see what exactly is causing your frame drops?

What is the point of this code? It looks like collision avoidance code, but you’re using a NavigationAgent2D. You should be pairing that with a NavigationRegion2D which should already be doing this work.

This code is triggering 60 times a second and testing everything the raycast is hitting. If you were to profile your code, this is most likely the problem. Along with what @pauldrewett pointed out.

And also, your move() function calls an enemy.play() function that isn’t listed, but if I had to bet, probably shouldn’t be getting called every frame either.

1 Like