Search code examples
path-findinggame-developmentgodot

In Godot the path returned by get_simple_path() seems offset by something


Just learning Godot, so maybe missing something obvious I am trying to have the player navigate towards a point clicked on the map. The path is calculated with some sort of offset I can't figure out.

Any pointers appreciated!

There is a very minimal replication of the problem here https://github.com/kender99/Godot_path_finding_problem_demo

On the image the white dot is the mouse click and the red is the path generatedenter image description here

The likely offending code is:

extends Node2D

var path : = PoolVector2Array()

func _unhandled_input(event):
    if event is InputEventMouseButton:
        if event.button_index == BUTTON_LEFT and event.pressed:
            path = $Navigation2D.get_simple_path($Player.position, event.position)
            $Player.path = path         
            $Line2D.points = path
            print(path.size(), ' Path:',path, '  Player:', $Player.position, '  Target:', event.position)           
            update()  # so line and circles get drawn

func _draw():
    for p in path:
                draw_circle(p, 5, Color(200, 200, 200))
    

Solution

  • event.position is the local position regards the current respondent, you should convert the event position to the local one of Navigation2D instead, like this:

    path = $Navigation2D.get_simple_path($Player.position, $Navigation2D.to_local(event.position))
    

    or use get_global_mouse_position() method like this:

    path = $Navigation2D.get_simple_path($Player.position, $Navigation2D.to_local(get_global_mouse_position()))