kakozuzo/Code/KPTLConnect.cs
2024-10-30 13:33:29 +03:00

99 lines
2.4 KiB
C#

using System;
using System.Threading.Tasks;
using Sandbox.Utility;
namespace Sandbox;
[Title( "[KPTL] 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<GameObject> 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);
}
}
/// <summary>
/// A client is fully connected to the server. This is called on the host.
/// </summary>
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!" );
}
/// <summary>
/// Find the most appropriate place to respawn
/// </summary>
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<SpawnPoint>().ToArray();
if ( spawnPoints.Length > 0 )
{
return Random.Shared.FromArray( spawnPoints ).Transform.World;
}
//
// Failing that, spawn where we are
//
return Transform.World;
}
}