Navigation broke when changing organization
Asked Answered
E

1

0

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.

Eris answered 16/3 at 18:8 Comment(0)
E
0

Your target is an export. Remove @export. Exports are shared between instances of the scene. So when target is null it does nothing.
The other problem may be get_node. Tilemap is in the main scene but you are retrieving it with $...
Use get_tree() to get the tree and then get the node or put tilemap in a group and use get_nodes_in_group and get the first one [0].

Ensue answered 24/3 at 1:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.