Fronter/Networking.gd

90 lines
2.7 KiB
GDScript

extends Node
var my_ip
var peer
var player_info = {}
var my_info = { name = "", color = Color8(255, 0, 255) }
var server_ip
func _ready():
my_ip = IP.get_local_addresses()[1]
prints(my_ip)
$YourIP.text = str("Your IP address:", my_ip)
get_tree().connect("network_peer_connected", self, "_player_connected")
get_tree().connect("network_peer_disconnected", self, "_player_disconnected")
get_tree().connect("connected_to_server", self, "_connected_ok")
get_tree().connect("connection_failed", self, "_connected_fail")
get_tree().connect("server_disconnected", self, "_server_disconnected")
get_tree().paused = true
func _on_Server_pressed():
peer = NetworkedMultiplayerENet.new()
peer.create_server(6969, 8)
get_tree().set_network_peer(peer)
get_tree().set_meta("network_peer", peer)
prints(get_tree().is_network_server())
prints(get_tree().has_network_peer())
prints(my_info)
func _on_Client_pressed():
peer = NetworkedMultiplayerENet.new()
peer.create_client(server_ip, 6969)
get_tree().set_network_peer(peer)
get_tree().set_meta("network_peer", peer)
prints(get_tree().is_network_server())
prints(get_tree().has_network_peer())
func _player_connected(id):
prints("AYYYYYYYYY ", id)
func _player_disconnected(id):
prints("OH NO ", id)
player_info.erase(id) # Erase player from info
func _connected_ok():
# Only called on clients, not server. Send my ID and info to all the other peers
rpc("register_player", get_tree().get_network_unique_id(), my_info)
func _server_disconnected():
pass # Server kicked us, show error and abort
func _connected_fail():
pass # Could not even connect to server, abort
remote func move_player(id, position):
prints("NETWORKING SAYS:", id, position)
pass
remote func register_player(id, info):
player_info[id] = info
if get_tree().is_network_server():
# Send my info to new player
rpc_id(id, "register_player", 1, my_info)
# Send the info of existing players
for peer_id in player_info:
rpc_id(id, "register_player", peer_id, player_info[peer_id])
prints(player_info[id], id)
# Call function to update lobby UI here
func _on_Name_pressed():
my_info = { name = $LineEdit.text, color = Color8(18, 255, 18) }
func _on_LineEdit_text_entered(new_text):
my_info = {name = new_text, color = my_info.color}
$UsernameLabel.text = str("Your netname is \"", new_text, "\"")
func _on_Server_Entry_text_entered(new_text):
server_ip = new_text
func _on_BackToMain_pressed():
$Server.visible = false
$Client.visible = false
$Name.visible = false
$UsernameEntry.visible = false
$ServerEntry.visible = false
$YourIP.visible = false
$UsernameLabel.visible = false
$BackToMain.visible = false
$ColorRect.visible = false