参考

场景设置

image.pngimage.png
image.png
image.png

  1. extends Navigation2D
  2. var start_point = Vector2()
  3. var end_point = Vector2()
  4. var path = []
  5. func _input(event):
  6. if event is InputEventMouseButton and event.pressed:
  7. if event.button_index == BUTTON_LEFT:
  8. print('button pressed left')
  9. start_point = event.position
  10. elif event.button_index == BUTTON_RIGHT:
  11. print('button pressed right')
  12. end_point = event.position
  13. func _process(delta):
  14. path = get_simple_path(start_point,end_point,false)
  15. update()
  16. func _draw():
  17. for point in path:
  18. draw_circle(point,10,Color(1,1,1))
  19. draw_polyline(path,Color(1,0,0),3,true)

image.png
image.pngimage.png

  1. extends Navigation2D
  2. var target_pos
  3. var path = []
  4. var speed = 500.0
  5. var can_move = false
  6. onready var player = $Sprite
  7. func _input(event):
  8. if event is InputEventMouseButton and event.pressed:
  9. if event.button_index == BUTTON_LEFT:
  10. target_pos = event.position
  11. path = get_simple_path(player.position,target_pos,false)
  12. update()
  13. can_move = true
  14. func _process(delta):
  15. if can_move:
  16. if path.size()>=2:
  17. var now_pos = player.position
  18. var dis = now_pos.distance_to(path[1])
  19. if dis > 5:
  20. player.position = now_pos.linear_interpolate(path[1],speed * delta/dis)
  21. else:
  22. player.position = path[1]
  23. path.remove(0)
  24. else:
  25. can_move = false
  26. func _draw():
  27. for point in path:
  28. draw_circle(point,10,Color(1,1,1))
  29. draw_polyline(path,Color(1,0,0),3,true)

运行效果

22229922.gif