using System; using System.Threading.Tasks; using Sandbox.Utility; namespace Sandbox; [Title( "Connect" )] [Category( "KPTL" )] [Icon( "electrical_services" )] public sealed class KPTLConnect : Component, Component.INetworkListener { [Property] public bool StartServer { get; set; } = true; [Property] public GameObject PlayerPrefab { get; set; } [Property] public List SpawnPoints { get; set; } protected override async Task OnLoad() { if ( Scene.IsEditor ) return; if ( StartServer && !Networking.IsActive ) { LoadingScreen.Title = "Creating Lobby"; await Task.DelayRealtimeSeconds( 0.1f ); Networking.CreateLobby(); } else if (!StartServer && !Networking.IsActive) { string lobbyId = await Http.RequestStringAsync( "https://sbox.koptilnya.xyz" ); Networking.Connect(lobbyId); } } /// /// A client is fully connected to the server. This is called on the host. /// public void OnActive( Connection channel ) { Log.Info( $"Player '{channel.DisplayName}' has joined the game" ); if ( !PlayerPrefab.IsValid() ) return; // // Find a spawn location for this player // var startLocation = FindSpawnLocation().WithScale( 1 ); // Spawn this object and make the client the owner var player = PlayerPrefab.Clone( startLocation, name: $"Player - {channel.DisplayName}" ); player.NetworkSpawn( channel ); if ( Networking.IsHost ) { Task.RunInThreadAsync( UpdateLobbyId ); } } private async Task UpdateLobbyId() { await Task.DelayRealtimeSeconds( 2f ); var lobbyList = await Networking.QueryLobbies(); await Http.RequestAsync( $"https://sbox.koptilnya.xyz/?text={lobbyList[0].LobbyId}", "POST" ); Log.Info( "Lobby ID updated successfully!" ); } /// /// Find the most appropriate place to respawn /// Transform FindSpawnLocation() { // // If they have spawn point set then use those // if ( SpawnPoints is not null && SpawnPoints.Count > 0 ) { return Random.Shared.FromList( SpawnPoints, default ).Transform.World; } // // If we have any SpawnPoint components in the scene, then use those // var spawnPoints = Scene.GetAllComponents().ToArray(); if ( spawnPoints.Length > 0 ) { return Random.Shared.FromArray( spawnPoints ).Transform.World; } // // Failing that, spawn where we are // return Transform.World; } }