Space-Smash-Out/Assets/Scripts/Managers/PlayerManager.cs
Jakob Feldmann 94863a7eb5 feat: free fly arena, 4-player support, 4-player arena, test-scene option etc.
There is also overhauled camera zoom behavior, an update to the match logic,
tweaks to the main menu scene.
2024-05-05 17:53:56 +02:00

107 lines
2.8 KiB
C#

using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using log4net;
using UnityEngine;
using UnityEngine.InputSystem;
namespace Managers
{
/// <summary>
/// Handles setting up and managing all local players.
/// </summary>
public class PlayerManager : MonoBehaviour
{
private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Globally accessible member to use manager with.
/// </summary>
public static PlayerManager G { get; private set; }
/// <summary>
/// The player which has started/owns the game.
/// May be identified at the start of the game and not
/// to be changed.
/// </summary>
public Player OnlinePlayer { get; private set; }
/// <summary>
/// List of the players currently playing the game.
/// </summary>
public List<Player> MatchPlayers { get; private set; } = new List<Player>();
[SerializeReference]
private CameraOperator cameraOperator;
void Awake()
{
G = this;
Log.Info("Awake");
}
/// <summary>
/// Create the minimum number of players for the match and
/// add them to the player list.
/// </summary>
/// <param name="minPlayers">Minimum number of players</param>
public void LocalMatchJoinPlayers(int minPlayers, int maxPlayers)
{
if (MatchPlayers.Count < minPlayers)
{
for (int i = MatchPlayers.Count; i < minPlayers; ++i)
{
CreateLocalPlayer(i + 1);
}
}
if (MatchPlayers.Count > maxPlayers)
{
MatchPlayers.RemoveRange(maxPlayers, MatchPlayers.Count - maxPlayers);
}
}
/// <summary>
/// Creates a new player for this local session.
/// </summary>
/// <param name="id">Number of the player</param>
/// <returns>The created player or null if the number was already choosen.</returns>
private Player CreateLocalPlayer(int id)
{
if (MatchPlayers.Any(p => p.playerNumber == id))
{
Log.Warn($"The local player with the number: {id}, already exists!");
return null;
}
Player player = ScriptableObject.CreateInstance<Player>();
player.playerNumber = id;
player.playerName = $"Player {id}";
MatchPlayers.Add(player);
Log.Debug($"Added player number {id}.");
return player;
}
/// <summary>
/// When playing online there is only one player per client.
/// TODO: No online syncronization at this point yet.
/// Just the spawned character/ships are syncronized.
/// </summary>
public void LoadOnlinePlayer()
{
Player player = ScriptableObject.CreateInstance<Player>();
player.playerNumber = 1;
player.playerName = $"Player {1}";
MatchPlayers.Add(player);
Log.Debug($"Added player number {1}.");
OnlinePlayer = player;
MatchPlayers = new List<Player>() { OnlinePlayer };
}
public void OnPlayerJoined(PlayerInput pi)
{
cameraOperator.AddCharacter(pi.gameObject);
}
}
}