Game.gd 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. extends Node2D
  2. onready var cam = $MainCamera
  3. export var dist_max = 900
  4. export var zoom_rate = 0.001
  5. var level
  6. var playerScene = preload("res://Player.tscn")
  7. func _ready():
  8. pass
  9. func _process(_d):
  10. move_camera()
  11. func _unhandled_input(event):
  12. if event.is_action("ui_accept") and event.is_pressed():
  13. if get_tree().has_group("living"):
  14. var living = get_tree().get_nodes_in_group("living")
  15. if !living.empty():
  16. return
  17. start()
  18. func start():
  19. # Clear if required
  20. if (get_tree().has_group("players")):
  21. var players = get_tree().get_nodes_in_group("players")
  22. for p in players:
  23. p.queue_free()
  24. if (level):
  25. level.queue_free()
  26. # Load level
  27. level = preload("res://Levels/Lab.tscn").instance()
  28. add_child(level)
  29. # Create players
  30. var player
  31. # Player 1
  32. player = playerScene.instance()
  33. player.grid = level
  34. player.turn_left_action = "player_1_turn_left"
  35. player.turn_right_action = "player_1_turn_right"
  36. player.position = Vector2(4 * 64 + 32, 8 * 64 + 32)
  37. add_child(player)
  38. # Player 2
  39. player = playerScene.instance()
  40. player.grid = level
  41. player.turn_left_action = "player_2_turn_left"
  42. player.turn_right_action = "player_2_turn_right"
  43. player.position = Vector2(6 * 64 + 32, 8 * 64 + 32)
  44. add_child(player)
  45. # TODO Timer
  46. get_tree().call_group("players", "_on_game_start")
  47. func move_camera():
  48. if !get_tree().has_group("players"):
  49. return
  50. var living
  51. if get_tree().has_group("living"):
  52. living = get_tree().get_nodes_in_group("living")
  53. if !living or living.size() == 0:
  54. # Show every players
  55. var players = get_tree().get_nodes_in_group("players")
  56. center_on(players)
  57. else:
  58. # Show remaining players only
  59. center_on(living)
  60. func center_on(players):
  61. var position_accumulator = Vector2(0.0, 0.0)
  62. for p in players:
  63. position_accumulator += p.position
  64. cam.position = position_accumulator / players.size()
  65. var dist = 0
  66. for i in range(players.size() - 1):
  67. for j in range(i + 1, players.size()):
  68. dist = max(dist, players[i].position.distance_to(players[j].position))
  69. # Extend camera zoom if liners are far from each other
  70. var zoom = 1.0
  71. if dist > dist_max:
  72. zoom += (dist - dist_max) * zoom_rate
  73. cam.zoom = Vector2(zoom, zoom)