character.gd 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. extends CharacterBody2D
  2. var movement_speed := 200.0
  3. @onready var navigation_agent: NavigationAgent2D = $NavigationAgent2D
  4. func _ready() -> void:
  5. # These values need to be adjusted for the actor's speed
  6. # and the navigation layout.
  7. navigation_agent.path_desired_distance = 2.0
  8. navigation_agent.target_desired_distance = 2.0
  9. navigation_agent.debug_enabled = true
  10. # The "click" event is a custom input action defined in
  11. # Project > Project Settings > Input Map tab.
  12. func _unhandled_input(event: InputEvent) -> void:
  13. if not event.is_action_pressed("click"):
  14. return
  15. set_movement_target(get_global_mouse_position())
  16. func set_movement_target(movement_target: Vector2) -> void:
  17. navigation_agent.target_position = movement_target
  18. func _physics_process(_delta: float) -> void:
  19. if navigation_agent.is_navigation_finished():
  20. return
  21. var current_agent_position: Vector2 = global_position
  22. var next_path_position: Vector2 = navigation_agent.get_next_path_position()
  23. velocity = current_agent_position.direction_to(next_path_position) * movement_speed
  24. move_and_slide()