player_manager.gd 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. class_name PlayerManager
  2. extends Node2D
  3. const SPAWN_RANDOM := 100.0
  4. const SPAWN_HEIGHT := 200.0
  5. @onready var player_pool: Node2D = $PlayerPool
  6. func _ready():
  7. # We only need to spawn players on the server.
  8. if not multiplayer.is_server():
  9. return
  10. multiplayer.peer_connected.connect(add_player)
  11. multiplayer.peer_disconnected.connect(del_player)
  12. # Spawn already connected players
  13. for id in multiplayer.get_peers():
  14. add_player(id)
  15. # Spawn the local player unless this is a dedicated server export.
  16. if not OS.has_feature("dedicated_server"):
  17. add_player(1)
  18. func _exit_tree():
  19. if not multiplayer.is_server():
  20. return
  21. multiplayer.peer_connected.disconnect(add_player)
  22. multiplayer.peer_disconnected.disconnect(del_player)
  23. func add_player(id: int):
  24. var character = preload("res://component/entity/jumper/jumper.tscn").instantiate()
  25. # Set player id.
  26. character.player = id
  27. # Randomize character position.
  28. character.position = Vector2(randf() * SPAWN_RANDOM, SPAWN_HEIGHT)
  29. character.name = str(id)
  30. player_pool.add_child(character, true)
  31. func del_player(id: int):
  32. if not player_pool.has_node(str(id)):
  33. return
  34. player_pool.get_node(str(id)).queue_free()