level.gd 1.1 KB

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