Pathfinding to a position

Godot Version

4.5

Question

Hi, I'm trying to make a top down 2D game and I'm trying to get an enemy to path find to a point on the map but the enemy isn't going to the right place. Could you take a look at my code to see if there is anything wrong with it? No matter what coordinates I put in the enemy always goes to the same place.

extends CharacterBody2D
@onready var creature = $"."
@onready var nav_agent = $NavigationAgent2D as NavigationAgent2D
@onready var nav_tiles = $"../Tiles/NavTiles"
#@onready var path_update_timer = $PathUpdateTimer

const speed = 100

func _physics_process(_delta: float) -> void:
	
	var current_pos = get_tile_coords()
	var next_path_pos = nav_agent.get_next_path_position().normalized()
	var dir = Vector2(current_pos).direction_to(next_path_pos)
	velocity = dir * speed
	move_and_slide()

func get_tile_coords():
	var tilemap := $"../Tiles/NavTiles"
	var local_pos = tilemap.to_local(global_position)
	var cell = tilemap.local_to_map(local_pos)
	return cell

func make_path(destination):
	nav_agent.target_position = destination
	nav_tiles.set_cell(destination, -1)

func _on_path_update_timer_timeout() -> void:
	make_path(Vector2(-9,-9))

Never mind I used the example code from this website.

1 Like