AutoScrollContainer.gd 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. @tool
  2. class_name AutoScrollContainer
  3. extends ScrollContainer
  4. var is_focused := false
  5. @export_enum("Wave", "Endless") var mode := 0
  6. @export_enum("Horizontal", "Vertical") var direction := 0
  7. var scroll_direction := "scroll_vertical"
  8. var scroll := 0.0
  9. @export var is_active := false
  10. @export var auto_connect_focus := true
  11. @export var auto_minimum_resize := false
  12. func _ready() -> void:
  13. scroll_direction = "scroll_horizontal" if direction == 0 else "scroll_vertical"
  14. set_focused(is_active)
  15. if auto_connect_focus:
  16. owner.focus_entered.connect(set_focused.bind(true))
  17. owner.focus_exited.connect(set_focused.bind(false))
  18. if auto_minimum_resize:
  19. get_child(0).resized.connect(update_sizing)
  20. func set_focused(enabled := false) -> void:
  21. is_focused = enabled
  22. func _physics_process(delta: float) -> void:
  23. wave(delta)
  24. func update_sizing() -> void:
  25. custom_minimum_size.x = clamp(get_child(0).size.x, 0, 100)
  26. var scroll_pos := 0.0
  27. var scroll_speed := 16.0 # pixels per second
  28. var move_direction := 1
  29. func wave(delta: float) -> void:
  30. if not is_focused:
  31. scroll_pos = 0
  32. set_deferred(scroll_direction, -1)
  33. var total_range := 0.0
  34. if direction == 0:
  35. total_range = get_child(0).size.x - size.x
  36. else:
  37. total_range = (get_child(0).size.y) - (size.y + 8)
  38. if total_range <= 0:
  39. return
  40. if scroll_pos > total_range + 16 or scroll_pos <= -16:
  41. move_direction *= -1
  42. scroll_pos += scroll_speed * move_direction * delta
  43. if direction == 0:
  44. scroll_horizontal = scroll_pos
  45. else:
  46. scroll_vertical = scroll_pos
  47. func endless(delta: float) -> void:
  48. scroll = wrap(scroll - delta, 0, 1)
  49. var amount = lerpf(0.0, get_child(0).size.x - size.x, scroll)
  50. scroll_horizontal = amount