Hey all, I'm playing around with 2D navigation and I had it (mostly) working. I had a tilemap and a navigation region as siblings to my unit, which was a characterbody2D node with sprite2D, collisionShape2D, navigationAgent2D, and timer children. It was set to move the unit to where I left click. I wanted to be able to spawn new units, so I packaged up the unit as a separate scene. I dropped the scene back into the main scene to test if things still worked, but now the unit doesn't move anymore. Here's the script attached to the unit that was making things work beforehand:
extends CharacterBody2D
@export var target: Vector2i
var mouse_pos
var speed = 64
var acceleration = 32
@onready var nav_agent: NavigationAgent2D = $UnitNav
@onready var tilemap = get_node("../TileMap")
func _physics_process(delta):
var direction = Vector2.ZERO
if Input.is_action_just_pressed("LMB"):
mouse_pos = get_global_mouse_position()
target = tilemap.local_to_map(tilemap.to_local(mouse_pos))
direction = nav_agent.get_next_path_position() - global_position
direction = direction.normalized()
velocity = velocity.lerp(direction * speed, acceleration * delta)
move_and_slide()
func _on_nav_timer_timeout():
if target:
nav_agent.target_position = tilemap.map_to_local(target)
nav_agent.target_position.x -= 32
nav_agent.target_position.y -= 32
I'd welcome any suggestions for fixing it. On top of that, my navigation continuously overshoots the destination and vibrates around the destination. The only workarounds I see that would be provided by the documentation are "close enough" solutions where I get near the destination and then stop moving. I'd also appreciate advice on that issue.
Thanks!
Edit: Sorry about the poor spacing on the snippet, the post editor doesn't seem to want to let me indent.