Advertisement
lazuee

Godot Click and Move, NavigationAgent2D

Sep 26th, 2022
569
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Godot GLSL 1.74 KB | Source Code | 0 0
  1. extends CharacterBody2D
  2.  
  3.  
  4. signal path_changed(path : PackedVector2Array)
  5.  
  6. @export var walk_speed := 200.0
  7. @onready var _agent : NavigationAgent2D = null
  8.  
  9. var _velocity := Vector2.ZERO
  10. var target = null
  11.  
  12. func _ready():
  13.     for child in self.get_children():
  14.         if child.get_class() == "NavigationAgent2D":
  15.             _agent = child
  16.             break
  17.  
  18.     if _agent == null:
  19.         _agent = NavigationAgent2D.new()
  20.         self.add_child(_agent)
  21.        
  22.     if _agent != null:
  23.         set_target_location(self.position)
  24.         _agent.path_changed.connect(_on_path_changed)
  25.         _agent.velocity_computed.connect(_on_velocity_computed)
  26.         _agent.target_reached.connect(_on_target_reached)
  27.         _agent.max_speed = walk_speed
  28.         _agent.avoidance_enabled = true
  29.  
  30. func set_target_location(mouse_target: Vector2) -> void:
  31.     _agent.set_target_location(mouse_target)
  32.     target = _agent.get_final_location()
  33.  
  34. func _physics_process(delta):
  35.     if not visible and not target: return
  36.  
  37.     var target_global_position := _agent.get_next_location()
  38.     var direction := self.global_transform.origin.direction_to(target_global_position)
  39.     var desired_velocity := direction * _agent.max_speed
  40.     var steering = (desired_velocity - _velocity) * delta * 4.0
  41.     _velocity += steering
  42.     _agent.set_velocity(_velocity)
  43.  
  44. func _on_path_changed():
  45.     var path = _agent.get_nav_path()
  46.     self.path_changed.emit(path)
  47.  
  48. func _on_velocity_computed(safe_velocity):
  49.     velocity = safe_velocity
  50.     if not _agent.is_navigation_finished():
  51.         # move the player, if not finished
  52.         move_and_slide()
  53.     else:
  54.         self.global_transform.origin = NavigationServer2D.map_get_closest_point(_agent.get_navigation_map(), self.global_transform.origin)
  55.  
  56. func _on_target_reached():
  57.     print(["_on_target_reached"])
  58.    
  59.     self.path_changed.emit([])
  60.     target = null;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement