Space-Smash-Out/Assets/Scripts/Managers/PlayerManager.cs

108 lines
2.8 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Xml.Serialization;
using log4net;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.Video;
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)
{
if (MatchPlayers.Count < minPlayers)
{
for (int i = MatchPlayers.Count; i < minPlayers; ++i)
{
CreateLocalPlayer(i + 1);
}
}
}
/// <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.AddPlayer(pi.gameObject);
}
}
}