godot-webrtc-mplayer-testing/scripts/screens/game.gd
2021-12-17 17:10:56 -06:00

59 lines
2 KiB
GDScript

extends Control
onready var player_obj = preload("res://objects/player.tscn")
export(NodePath) onready var camera = get_node(camera) as Camera2D
export(NodePath) onready var menu = get_node(menu) as PopupDialog
onready var zoom_levels = [0.25, 0.5, 1, 1.5, 2, 2.5, 3]
onready var current_zoom_level_index = 2
onready var player = null
onready var players = null
func _ready():
# TODO: probably have to wait for all peers to be ready before we add players
# camera.zoom = Vector2(0.25, 0.25)
Global.client.connect("webrtc_peer_disconnected", self, "_webrtc_peer_disconnected")
if Global.client.is_host():
for id in get_tree().get_network_connected_peers():
Global.client.peers[id].ready = false
ready(1)
else:
rpc("ready", get_tree().get_network_unique_id())
remotesync func ready(id):
print("Ready %d" % id)
Global.client.peers[id].ready = true
var all_ready = true
for id in Global.client.peers: all_ready = all_ready and Global.client.peers[id].ready
if all_ready: start()
func _webrtc_peer_disconnected(id):
if Global.client.peers[id].has("player"):
Global.client.peers[id].player.queue_free()
func start():
print("Starting Game...")
# for each peer
for id in Global.client.peers:
print("Creating player for peer %d (name: %s)" % [id, Global.client.peers[id].name])
rpc("add_player", id, Global.client.peers[id].name)
func _process(_delta):
if player: camera.offset = player.position
remotesync func add_player(id, name):
var new_player = player_obj.instance()
if id == get_tree().get_network_unique_id(): player = new_player
new_player.name = str(id)
new_player.set_network_master(id)
add_child(new_player)
new_player.global_position = Vector2(-400 + (id % 800), -400 + (id % 800))
print("Added player: %s for peer %s named %s" % [new_player, id, name])
Global.client.peers[id].player = new_player
new_player.display_name = name
func _on_leave_pressed(): Global.main_menu()
func _on_menu_button_pressed(): menu.popup_centered()
func _on_close_pressed(): menu.hide()