Last active
February 13, 2021 16:59
-
-
Save Jummit/351d25cff379ab24f392d9b50028da9a to your computer and use it in GitHub Desktop.
server and client on the same machine using custom_multiplayer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends Node | |
# this script is attached to the main scene | |
var server_api := MultiplayerAPI.new() | |
var client_api := MultiplayerAPI.new() | |
# The actual main scene of the game. It is instanced in the script. | |
export var game_scene : PackedScene | |
func _ready(): | |
get_tree().connect("node_added", self, "_on_SceneTree_node_added") | |
# create the server root node | |
var server := Viewport.new() | |
server.name = "Server" | |
server.own_world = true | |
# add the node to the scene tree | |
get_tree().root.call_deferred("add_child", server) | |
# add a game instance to it | |
server.add_child(game_scene.instance()) | |
# create the server networking peer | |
var server_peer := NetworkedMultiplayerENet.new() | |
server_peer.create_server(4666) | |
server_api.network_peer = server_peer | |
# By default the root node is the root of the scene tree. | |
# This sets it to be the server root node we created earlier. | |
server_api.set_root_node(server) | |
server.custom_multiplayer = server_api | |
# create the client root node | |
var client := Node.new() | |
client.name = "Client" | |
# Add another game instance to the client root node. | |
# As a result, two instances of the game run at the same time; the server's and the client's. | |
client.add_child(game_scene.instance()) | |
# add the node to the scene tree | |
get_tree().root.call_deferred("add_child", client) | |
# create the client networking peer | |
var client_peer := NetworkedMultiplayerENet.new() | |
client_peer.create_client("localhost", 4666) | |
client_api.network_peer = client_peer | |
# set the root node to be the client root node created earlier | |
client_api.set_root_node(client) | |
client.custom_multiplayer = client_api | |
func _on_SceneTree_node_added(node : Node): | |
# custom_multiplayer has to be set for each node that is created while the game is running | |
# the multiplayer peer is chosen depending on if they are under the server or the client tree | |
if node.find_parent("Server"): | |
node.custom_multiplayer = server_api | |
elif node.find_parent("Client"): | |
node.custom_multiplayer = client_api | |
func _process(_delta): | |
# Poll the networking peers. This makes them recieve and send rpcs and packets. | |
server_api.poll() | |
client_api.poll() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment