MainCamera.gd 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. extends Camera2D
  2. # Handle zoom and move for keeping focus points in view
  3. export var zoom_border = 100
  4. var zoom_rate:float
  5. var dist_max_x:float
  6. var dist_max_y:float
  7. var view:Viewport
  8. func _ready():
  9. view = get_tree().root
  10. view.connect("size_changed", self, "_on_size_changed")
  11. update_zoom_reference()
  12. func _process(_d):
  13. move()
  14. func move():
  15. if !get_tree().has_group("liners"):
  16. return
  17. var running
  18. if get_tree().has_group("running"):
  19. running = get_tree().get_nodes_in_group("running")
  20. if !running or running.size() == 0:
  21. # Show every liners
  22. var liners = get_tree().get_nodes_in_group("liners")
  23. center_on(liners)
  24. else:
  25. # Show remaining liners only
  26. center_on(running)
  27. func center_on(focus_points: Array) -> void:
  28. # Focus middle point
  29. var last_point: Node2D = focus_points.pop_back()
  30. var position_min: Vector2
  31. if last_point:
  32. position_min = last_point.position
  33. else:
  34. position_min = Vector2(0.0, 0.0)
  35. var position_max := position_min
  36. for p in focus_points:
  37. position_min.x = min(p.position.x, position_min.x)
  38. position_min.y = min(p.position.y, position_min.y)
  39. position_max.x = max(p.position.x, position_max.x)
  40. position_max.y = max(p.position.y, position_max.y)
  41. position = (position_min + position_max) / 2
  42. # Extend camera zoom if focus points are far from each other
  43. var dist_x: float = position_max.x - position_min.x
  44. var dist_y: float = position_max.y - position_min.y
  45. var new_zoom: float = 1.0
  46. if dist_x > dist_max_x:
  47. new_zoom += (dist_x - dist_max_x) * zoom_rate
  48. if dist_y > dist_max_y:
  49. new_zoom = max(new_zoom, 1.0 + (dist_y - dist_max_y) * zoom_rate)
  50. zoom = Vector2(new_zoom, new_zoom)
  51. func update_zoom_reference():
  52. dist_max_x = view.size.x - 2 * zoom_border
  53. dist_max_y = view.size.y - 2 * zoom_border
  54. zoom_rate = 1.0 / min(dist_max_x, dist_max_y)
  55. func _on_size_changed():
  56. update_zoom_reference()