MainCamera.gd 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. extends Camera2D
  2. export var zoom_border = 100
  3. var zoom_rate:float
  4. var view:Viewport
  5. var dist_max:float
  6. func _ready():
  7. view = get_tree().root
  8. view.connect("size_changed", self, "_on_size_changed")
  9. update_zoom_reference()
  10. func _process(_d):
  11. move()
  12. func move():
  13. if !get_tree().has_group("players"):
  14. return
  15. var running
  16. if get_tree().has_group("running"):
  17. running = get_tree().get_nodes_in_group("running")
  18. if !running or running.size() == 0:
  19. # Show every players
  20. var players = get_tree().get_nodes_in_group("players")
  21. center_on(players)
  22. else:
  23. # Show remaining players only
  24. center_on(running)
  25. func center_on(players):
  26. var position_accumulator = Vector2(0.0, 0.0)
  27. for p in players:
  28. position_accumulator += p.position
  29. position = position_accumulator / players.size()
  30. var dist = 0
  31. for i in range(players.size() - 1):
  32. for j in range(i + 1, players.size()):
  33. dist = max(dist, players[i].position.distance_to(players[j].position))
  34. # Extend camera zoom if liners are far from each other
  35. var new_zoom = 1.0
  36. if dist > dist_max:
  37. new_zoom += (dist - dist_max) * zoom_rate
  38. zoom = Vector2(new_zoom, new_zoom)
  39. func update_zoom_reference():
  40. var ref_length = min(view.size.x, view.size.y)
  41. dist_max = ref_length - 2 * zoom_border
  42. zoom_rate = 1.0 / dist_max
  43. func _on_size_changed():
  44. update_zoom_reference()