character.gd 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. extends Position2D
  2. export(float) var SPEED = 200.0
  3. enum STATES { IDLE, FOLLOW }
  4. var _state = null
  5. var path = []
  6. var target_point_world = Vector2()
  7. var target_position = Vector2()
  8. var velocity = Vector2()
  9. func _ready():
  10. _change_state(IDLE)
  11. func _change_state(new_state):
  12. if new_state == FOLLOW:
  13. path = get_parent().get_node('TileMap').get_path(position, target_position)
  14. if not path or len(path) == 1:
  15. _change_state(IDLE)
  16. return
  17. # The index 0 is the starting cell
  18. # we don't want the character to move back to it in this example
  19. target_point_world = path[1]
  20. _state = new_state
  21. func _process(delta):
  22. if not _state == FOLLOW:
  23. return
  24. var arrived_to_next_point = move_to(target_point_world)
  25. if arrived_to_next_point:
  26. path.remove(0)
  27. if len(path) == 0:
  28. _change_state(IDLE)
  29. return
  30. target_point_world = path[0]
  31. func move_to(world_position):
  32. var MASS = 10.0
  33. var ARRIVE_DISTANCE = 10.0
  34. var desired_velocity = (world_position - position).normalized() * SPEED
  35. var steering = desired_velocity - velocity
  36. velocity += steering / MASS
  37. position += velocity * get_process_delta_time()
  38. rotation = velocity.angle()
  39. return position.distance_to(world_position) < ARRIVE_DISTANCE
  40. func _input(event):
  41. if event.is_action_pressed('click'):
  42. if Input.is_key_pressed(KEY_SHIFT):
  43. global_position = get_global_mouse_position()
  44. else:
  45. target_position = get_global_mouse_position()
  46. _change_state(FOLLOW)