MainCamera.gd 1.4 KB

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