109 lines
2.7 KiB
C#
109 lines
2.7 KiB
C#
using System.Collections.Generic;
|
|
using System.Threading;
|
|
using Cysharp.Threading.Tasks;
|
|
using Game.Pathfinding;
|
|
using Sirenix.OdinInspector;
|
|
using UnityEngine;
|
|
|
|
namespace Game.Player;
|
|
|
|
public class PlayerManager : ManagerBase, IPlayerManager
|
|
{
|
|
private Dictionary<string, IPlayer> _players = new Dictionary<string, IPlayer>();
|
|
|
|
public IPlayer CreatePlayer(string playerName, string assetName)
|
|
{
|
|
var gameObject = Game.resourceManager.LoadGameObjectSync(assetName);
|
|
IPlayer player = new Player();
|
|
player.SetGameObject(gameObject, playerName);
|
|
this._players.Add(playerName, player);
|
|
return player;
|
|
}
|
|
|
|
public IPlayer GetPlayer(string playerName)
|
|
{
|
|
return this._players.GetValueOrDefault(playerName);
|
|
}
|
|
|
|
public void DeletePlayer(string playerName)
|
|
{
|
|
if (this._players.TryGetValue(playerName, out var player))
|
|
{
|
|
player.Dispose();
|
|
}
|
|
}
|
|
}
|
|
|
|
public interface IPlayerManager
|
|
{
|
|
//
|
|
IPlayer CreatePlayer(string playerName, string assetName);
|
|
|
|
IPlayer GetPlayer(string playerName);
|
|
|
|
void DeletePlayer(string playerName);
|
|
}
|
|
|
|
public interface IPlayer
|
|
{
|
|
string playerName { get; }
|
|
GameObject self { get; }
|
|
void SetGameObject(GameObject gameObject, string name);
|
|
UniTask<bool> MoveAsync(List<WayPoint> wayPoint, CancellationToken token);
|
|
void Dispose();
|
|
}
|
|
|
|
class PlayerInfo : MonoBehaviour
|
|
{
|
|
[SerializeField] [ReadOnly] private Player _player;
|
|
|
|
public void SetPlayer(Player player)
|
|
{
|
|
this._player = player;
|
|
gameObject.name = this._player.playerName;
|
|
}
|
|
}
|
|
|
|
internal class Player : IPlayer
|
|
{
|
|
private GameObject _self;
|
|
private string _playerName;
|
|
|
|
public string playerName => this._playerName;
|
|
|
|
public GameObject self => this._self;
|
|
|
|
public void SetGameObject(GameObject gameObject, string name)
|
|
{
|
|
this._self = gameObject;
|
|
this._playerName = name;
|
|
var playerInfo = this._self.AddComponent<PlayerInfo>();
|
|
playerInfo.SetPlayer(this);
|
|
}
|
|
|
|
public async UniTask<bool> MoveAsync(List<WayPoint> wayPoint, CancellationToken token)
|
|
{
|
|
foreach (var point in wayPoint)
|
|
{
|
|
bool isMoveing = true;
|
|
while (isMoveing)
|
|
{
|
|
await UniTask.Yield(token);
|
|
if (Vector3.Distance(self.transform.position, point.position) <= 0.1f)
|
|
{
|
|
isMoveing = false;
|
|
break;
|
|
}
|
|
|
|
this._self.transform.Translate(point.position);
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
GameObject.DestroyImmediate(self);
|
|
}
|
|
} |