character.gd 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. extends Node2D
  2. enum States { IDLE, FOLLOW }
  3. const MASS = 10.0
  4. const ARRIVE_DISTANCE = 10.0
  5. export(float) var speed = 200.0
  6. var _state = States.IDLE
  7. var _path = []
  8. var _target_point_world = Vector2()
  9. var _target_position = Vector2()
  10. var _velocity = Vector2()
  11. func _ready():
  12. _change_state(States.IDLE)
  13. func _process(_delta):
  14. if _state != States.FOLLOW:
  15. return
  16. var _arrived_to_next_point = _move_to(_target_point_world)
  17. if _arrived_to_next_point:
  18. _path.remove(0)
  19. if len(_path) == 0:
  20. _change_state(States.IDLE)
  21. return
  22. _target_point_world = _path[0]
  23. func _unhandled_input(event):
  24. if event.is_action_pressed("click"):
  25. var global_mouse_pos = get_global_mouse_position()
  26. if Input.is_key_pressed(KEY_SHIFT):
  27. global_position = global_mouse_pos
  28. else:
  29. _target_position = global_mouse_pos
  30. _change_state(States.FOLLOW)
  31. func _move_to(world_position):
  32. var desired_velocity = (world_position - position).normalized() * speed
  33. var steering = desired_velocity - _velocity
  34. _velocity += steering / MASS
  35. position += _velocity * get_process_delta_time()
  36. rotation = _velocity.angle()
  37. return position.distance_to(world_position) < ARRIVE_DISTANCE
  38. func _change_state(new_state):
  39. if new_state == States.FOLLOW:
  40. _path = get_parent().get_node("TileMap").get_astar_path(position, _target_position)
  41. if not _path or len(_path) == 1:
  42. _change_state(States.IDLE)
  43. return
  44. # The index 0 is the starting cell.
  45. # We don't want the character to move back to it in this example.
  46. _target_point_world = _path[1]
  47. _state = new_state