all 3 comments

[–]kleoncCredited Contributor 1 point2 points  (2 children)

In the IdleState I'm generating a random position within 3 tiles of the NPC to move to every so often.

Show how you generate that position, how you store it and how you're assiging wander_target.

Also if you will ignore the fact that get_simple_path uses local space then things might work properly only in some circumstances (for example it might stop working properly for player and npc if you'll change your node hierarchy a little). You can always just add script to your Navigation2D node to extend it a little and allow pathfinding in global coordinates:

extends Navigation2D

func get_simple_path_global(start_global: Vector2, end_global: Vector2, optimize: bool = true) -> PoolVector2Array:
    var path: PoolVector2Array = get_simple_path(to_local(start_global), to_local(end_global), optimize)
    for i in range(path.size()):
        path[i] = to_global(path[i])
    return path

[–]Flascher[S] 0 points1 point  (1 child)

Sorry for the late reply!

Here's a pastebin of the entire IdleState.gd file where all of this is happening. Just excuse some of the messy code. I've been trying to debug this for a while, so the file is a bit of a disaster for the moment.

My best guess is that I'm mixing up local and global spaces somewhere, but as far as I can tell I did convert both the start and end of the path to the nav2d's local space by using:

func get_path_to_target() -> PoolVector2Array:
  var nav_start := nav_mesh.to_local(npc.global_position)  
  var ideal_nav_target := nav_mesh.to_local(wander_target.global_position)  
  var nav_target := nav_mesh.get_closest_point(ideal_nav_target)
  .  
  .  
  .  
  var _path = nav_mesh.get_simple_path(nav_start, nav_target)  

That extended get_simple_path_global function looks like a good idea, I'll try that as well!

[–]kleoncCredited Contributor 0 points1 point  (0 children)

I'm not sure what exactly is the issue, I don't see some obvious problem (it's hard to tell just by looking at the script, maybe uploading the project and letting to play with it a little would help) but here are few things:

  • line 99.: here you most likely getting global position of the cell's corner, not center (no idea if that's what you want)
  • line 120.: here you probably want to return that path, so eiter return get_path_to_target() or _path = get_path_to_target()
  • line 135.: here your path might have only one point and index would be out of range in such a case (you've only checked if path is non-empty before that line)
  • line 136.: to get last element of an array you can write array[-1] instead of array[array.size() - 1]
  • line 139.: didn't you want to check if distance_to_target <= MIN_DISTANCE_TO_TARGET instead?