multiplayer.gd 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. extends Node
  2. const PORT = 4433
  3. func _ready() -> void:
  4. # Start paused
  5. get_tree().paused = true
  6. # You can save bandwith by disabling server relay and peer notifications.
  7. multiplayer.server_relay = false
  8. # Automatically start the server in headless mode.
  9. if DisplayServer.get_name() == "headless":
  10. print("Automatically starting dedicated server")
  11. _on_host_pressed.call_deferred()
  12. func _on_host_pressed() -> void:
  13. # Start as server
  14. var peer = ENetMultiplayerPeer.new()
  15. peer.create_server(PORT)
  16. if peer.get_connection_status() == MultiplayerPeer.CONNECTION_DISCONNECTED:
  17. OS.alert("Failed to start multiplayer server")
  18. return
  19. multiplayer.multiplayer_peer = peer
  20. start_game()
  21. func _on_connect_pressed() -> void:
  22. # Start as client
  23. var txt : String = $UI/Net/Options/Remote.text
  24. if txt == "":
  25. OS.alert("Need a remote to connect to.")
  26. return
  27. var peer = ENetMultiplayerPeer.new()
  28. peer.create_client(txt, PORT)
  29. if peer.get_connection_status() == MultiplayerPeer.CONNECTION_DISCONNECTED:
  30. OS.alert("Failed to start multiplayer client")
  31. return
  32. multiplayer.multiplayer_peer = peer
  33. start_game()
  34. func start_game() -> void:
  35. # Hide the UI and unpause to start the game.
  36. $UI.hide()
  37. get_tree().paused = false
  38. # Only change level on the server.
  39. # Clients will instantiate the level via the spawner.
  40. if multiplayer.is_server():
  41. change_level.call_deferred(load("res://run/levels/destination/final.tscn"))
  42. # Call this function deferred and only on the main authority (server).
  43. func change_level(scene: PackedScene) -> void:
  44. # Remove old level if any.
  45. var level = $Level
  46. for c in level.get_children():
  47. level.remove_child(c)
  48. c.queue_free()
  49. # Add new level.
  50. level.add_child(scene.instantiate())
  51. # The server can restart the level by pressing HOME.
  52. func _input(event: InputEvent) -> void:
  53. if not multiplayer.is_server():
  54. return
  55. if event.is_action("ui_home") and Input.is_action_just_pressed("ui_home"):
  56. change_level.call_deferred(load("res://run/levels/destination/final.tscn"))