初始化提交
This commit is contained in:
74
Assets/Scripts/Manager/PlayerManager.cs
Normal file
74
Assets/Scripts/Manager/PlayerManager.cs
Normal file
@@ -0,0 +1,74 @@
|
||||
using System.Collections.Generic;
|
||||
using Google.Protobuf;
|
||||
using UnityEngine;
|
||||
|
||||
public class PlayerManager : MonoBehaviour
|
||||
{
|
||||
public GameObject playerPrefab;
|
||||
public Transform playerScene;
|
||||
|
||||
private Dictionary<long, PlayerMove> _players = new();
|
||||
|
||||
public static PlayerManager Instance { get; private set; }
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
if (Instance != null)
|
||||
{
|
||||
Destroy(gameObject);
|
||||
return;
|
||||
}
|
||||
|
||||
Instance = this;
|
||||
}
|
||||
|
||||
private void Start()
|
||||
{
|
||||
SocketMessageManager.Instance.Subscribe(MessageID.LoginSuccess, OnLoginSuccess);
|
||||
SocketMessageManager.Instance.Subscribe(MessageID.EnterInstance, OnEnterInstance);
|
||||
SocketMessageManager.Instance.Subscribe(MessageID.Position, OnPosition);
|
||||
SocketManager.Instance.Connect();
|
||||
}
|
||||
|
||||
private GameObject AddPlayer(PositionInfo info)
|
||||
{
|
||||
var player = Instantiate(playerPrefab, playerScene);
|
||||
player.GetComponent<PlayerInfo>().usn = info.USN;
|
||||
var move = player.GetComponent<PlayerMove>();
|
||||
move.SetPosition(info.X, info.Y);
|
||||
_players.Add(info.USN, move);
|
||||
return player;
|
||||
}
|
||||
|
||||
private void OnLoginSuccess(ByteString msg)
|
||||
{
|
||||
var loginSuccess = S2C_LoginSuccess.Parser.ParseFrom(msg);
|
||||
SocketManager.Instance.SendMessage(MessageID.EnterInstance, new C2S_EnterInstance
|
||||
{
|
||||
InstanceID = loginSuccess.InstanceID
|
||||
});
|
||||
}
|
||||
|
||||
private void OnEnterInstance(ByteString msg)
|
||||
{
|
||||
var enterInstance = S2C_EnterInstance.Parser.ParseFrom(msg);
|
||||
var player = AddPlayer(enterInstance.Info);
|
||||
player.AddComponent<PlayerControl>();
|
||||
}
|
||||
|
||||
private void OnPosition(ByteString msg)
|
||||
{
|
||||
var position = S2C_Position.Parser.ParseFrom(msg);
|
||||
foreach (var info in position.Info)
|
||||
{
|
||||
if (!_players.ContainsKey(info.USN))
|
||||
{
|
||||
AddPlayer(info);
|
||||
}
|
||||
else
|
||||
{
|
||||
_players[info.USN].SetPosition(info.X, info.Y);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
3
Assets/Scripts/Manager/PlayerManager.cs.meta
Normal file
3
Assets/Scripts/Manager/PlayerManager.cs.meta
Normal file
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5228fd1670b3455a9900c17b9c1899e6
|
||||
timeCreated: 1765791557
|
||||
129
Assets/Scripts/Manager/SocketManager.cs
Normal file
129
Assets/Scripts/Manager/SocketManager.cs
Normal file
@@ -0,0 +1,129 @@
|
||||
using System.Collections;
|
||||
using Google.Protobuf;
|
||||
using NativeWebSocket;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Networking;
|
||||
|
||||
[System.Serializable]
|
||||
public class LoginResponse
|
||||
{
|
||||
public int code;
|
||||
public string msg;
|
||||
public Data data;
|
||||
}
|
||||
|
||||
[System.Serializable]
|
||||
public class Data
|
||||
{
|
||||
public long usn;
|
||||
public string name;
|
||||
public string accessToken;
|
||||
public string refreshToken;
|
||||
}
|
||||
|
||||
public class SocketManager : MonoBehaviour
|
||||
{
|
||||
private WebSocket _ws;
|
||||
|
||||
public static SocketManager Instance { get; private set; }
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
if (Instance != null)
|
||||
{
|
||||
Destroy(gameObject);
|
||||
return;
|
||||
}
|
||||
|
||||
Instance = this;
|
||||
}
|
||||
|
||||
public async void Connect()
|
||||
{
|
||||
var token = await GetTokenAsync();
|
||||
|
||||
// _ws = new WebSocket($"wss://www.hlsq.asia/ws/?token={Random.Range(1, 1000)}");
|
||||
_ws = new WebSocket($"ws://127.0.0.1:8501/?token={token}");
|
||||
|
||||
_ws.OnOpen += () => { Debug.Log("Connection open!"); };
|
||||
|
||||
_ws.OnError += (e) => { Debug.Log("Error! " + e); };
|
||||
|
||||
_ws.OnClose += (e) => { Debug.Log("Connection closed!"); };
|
||||
|
||||
_ws.OnMessage += (bytes) =>
|
||||
{
|
||||
var message = Message.Parser.ParseFrom(bytes);
|
||||
Debug.Log("OnMessage: " + message.ID);
|
||||
SocketMessageManager.Instance.TriggerEvent(message.ID, message.Payload);
|
||||
};
|
||||
|
||||
await _ws.Connect();
|
||||
}
|
||||
|
||||
private async System.Threading.Tasks.Task<string> GetTokenAsync()
|
||||
{
|
||||
string token = "";
|
||||
var tcs = new System.Threading.Tasks.TaskCompletionSource<string>();
|
||||
|
||||
StartCoroutine(HttpPost("http://127.0.0.1:8503/gw/login", "{\"phone\": \"1234\", \"code\": \"1234\"}", (resp) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var r = JsonUtility.FromJson<LoginResponse>(resp);
|
||||
token = r.data.accessToken;
|
||||
tcs.SetResult(token);
|
||||
}
|
||||
catch (System.Exception e)
|
||||
{
|
||||
tcs.SetException(e);
|
||||
}
|
||||
}));
|
||||
|
||||
return await tcs.Task;
|
||||
}
|
||||
|
||||
public void SendMessage(MessageID id, IMessage msg)
|
||||
{
|
||||
var m = new Message
|
||||
{
|
||||
ID = id,
|
||||
Payload = ByteString.CopyFrom(msg.ToByteArray())
|
||||
};
|
||||
_ws.Send(m.ToByteArray());
|
||||
}
|
||||
|
||||
public IEnumerator HttpPost(string url, string jsonData, System.Action<string> callback)
|
||||
{
|
||||
var request = new UnityWebRequest(url, "POST");
|
||||
var bodyRaw = System.Text.Encoding.UTF8.GetBytes(jsonData);
|
||||
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
|
||||
request.downloadHandler = new DownloadHandlerBuffer();
|
||||
request.SetRequestHeader("Content-Type", "application/json");
|
||||
|
||||
yield return request.SendWebRequest();
|
||||
|
||||
if (request.result == UnityWebRequest.Result.Success)
|
||||
{
|
||||
callback?.Invoke(request.downloadHandler.text);
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogError("HTTP POST Error: " + request.error);
|
||||
}
|
||||
|
||||
request.Dispose();
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
#if !UNITY_WEBGL || UNITY_EDITOR
|
||||
_ws?.DispatchMessageQueue();
|
||||
#endif
|
||||
}
|
||||
|
||||
private async void OnApplicationQuit()
|
||||
{
|
||||
await _ws.Close();
|
||||
}
|
||||
}
|
||||
3
Assets/Scripts/Manager/SocketManager.cs.meta
Normal file
3
Assets/Scripts/Manager/SocketManager.cs.meta
Normal file
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d6b127b9486a4f07acfbdcc29fc7d2a5
|
||||
timeCreated: 1765791343
|
||||
55
Assets/Scripts/Manager/SocketMessageManager.cs
Normal file
55
Assets/Scripts/Manager/SocketMessageManager.cs
Normal file
@@ -0,0 +1,55 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Google.Protobuf;
|
||||
using UnityEngine;
|
||||
|
||||
public class SocketMessageManager : MonoBehaviour
|
||||
{
|
||||
// 使用字典存储
|
||||
private Dictionary<MessageID, Action<ByteString>> _eventDictionary;
|
||||
|
||||
public static SocketMessageManager Instance { get; private set; }
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
if (Instance != null)
|
||||
{
|
||||
Destroy(gameObject);
|
||||
return;
|
||||
}
|
||||
|
||||
Instance = this;
|
||||
_eventDictionary = new Dictionary<MessageID, Action<ByteString>>();
|
||||
}
|
||||
|
||||
// 订阅事件
|
||||
public void Subscribe(MessageID messageID, Action<ByteString> listener)
|
||||
{
|
||||
if (_eventDictionary.ContainsKey(messageID))
|
||||
{
|
||||
_eventDictionary[messageID] += listener;
|
||||
}
|
||||
else
|
||||
{
|
||||
_eventDictionary[messageID] = listener;
|
||||
}
|
||||
}
|
||||
|
||||
// 取消订阅
|
||||
public void Unsubscribe(MessageID messageID, Action<ByteString> listener)
|
||||
{
|
||||
if (_eventDictionary.ContainsKey(messageID))
|
||||
{
|
||||
_eventDictionary[messageID] -= listener;
|
||||
}
|
||||
}
|
||||
|
||||
// 触发事件
|
||||
public void TriggerEvent(MessageID messageID, ByteString data = null)
|
||||
{
|
||||
if (_eventDictionary.ContainsKey(messageID))
|
||||
{
|
||||
_eventDictionary[messageID]?.Invoke(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
3
Assets/Scripts/Manager/SocketMessageManager.cs.meta
Normal file
3
Assets/Scripts/Manager/SocketMessageManager.cs.meta
Normal file
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: afc9630f7f1a49b5b0e8b13bffa9b4ea
|
||||
timeCreated: 1765791087
|
||||
Reference in New Issue
Block a user