Hello, I'm doing a top-down shooter game currently and I recently started adding pathfinding, to make it more difficult for the enemies to be near their objective.
I started checking a template project about basic pathfinding, using Navigation2D and this what I got:
extends KinematicBody2D
var direction
var path: Array = []
var speed = 40
onready var plr = get_tree().get_root().get_node("Level/Scene/Player/Player")
func createPath():
path = get_tree().get_root().get_node("Level/Navigation2D").get_simple_path(global_position, plr.global_position, true)
path[0] = global_position
get_tree().get_root().get_node("Level/Line2D").points = path
func _ready():
createPath()
func move():
direction = move_and_slide(direction)
func navigate():
if path.size() > 0:
direction = global_position.direction_to(path[1]) * speed
if global_position == path[0]:
path.pop_front()
func _process(delta):
createPath()
navigate()
move()
Of course, some parts of the codes were not copied exactly and were modified for the game purpose. The top-down shooter game consists of infinite rounds of enemies appearing each amount of seconds, and after testing this method I found the next things
If I use createPath()
in the process function, when I get further from enemies, the game fps starts to decrease
If I use createPath()
in a Timer that changes the path every one second, each second will stop and will start moving weird from left to right and after will continue until the timer stops again and creates a new path.
It doesn't do the exact path and sometimes tries to cross over walls. (In this case, I didn't put cells where walls are, so the pathfinding system can interpret that cannot create a path over those parts, but for some reason, stills doing it. This happens, even more, when optimize option is enabled)
¿There's a way to fix this or to do a more efficient pathfinding system that doesn't sacrifice FPS when the player is far?