CollisionAvoidance/Assets/Scripts/WebSocketClient.cs

102 lines
2.8 KiB
C#

using UnityEngine;
using NativeWebSocket;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
public class WebSocketClient : MonoBehaviour
{
private WebSocket websocket;
private readonly string serverUrl = "ws://localhost:8080";
async void Start()
{
websocket = new WebSocket(serverUrl);
websocket.OnOpen += () =>
{
Debug.Log("Connection open!");
};
websocket.OnError += (e) =>
{
Debug.LogError($"Error! {e}");
};
websocket.OnClose += (e) =>
{
Debug.Log("Connection closed!");
};
websocket.OnMessage += (bytes) =>
{
var message = System.Text.Encoding.UTF8.GetString(bytes);
HandleMessage(message);
};
await websocket.Connect();
}
void Update()
{
#if !UNITY_WEBGL || UNITY_EDITOR
websocket.DispatchMessageQueue();
#endif
}
private void HandleMessage(string jsonMessage)
{
try
{
var json = JObject.Parse(jsonMessage);
string messageType = json["type"].ToString();
switch (messageType)
{
case "position_update":
HandlePositionUpdate(json);
break;
case "collision_warning":
HandleCollisionWarning(json);
break;
}
}
catch (System.Exception e)
{
Debug.LogError($"Error parsing message: {e.Message}");
}
}
private void HandlePositionUpdate(JObject json)
{
string objectId = json["objectId"].ToString();
string objectType = json["objectType"].ToString();
double longitude = json["longitude"].Value<double>();
double latitude = json["latitude"].Value<double>();
double heading = json["heading"].Value<double>();
// 更新对应物体的位置和朝向
GameObject obj = GameObject.Find(objectId);
if (obj != null)
{
Vector3 position = CoordinateConverter.ToUnityPosition(longitude, latitude);
obj.transform.position = position;
obj.transform.rotation = Quaternion.Euler(0, (float)heading, 0);
}
}
private void HandleCollisionWarning(JObject json)
{
string object1Id = json["object1Id"].ToString();
string object2Id = json["object2Id"].ToString();
string warningLevel = json["warningLevel"].ToString();
double distance = json["distance"].Value<double>();
// 显示碰撞警告效果
WarningManager.Instance.ShowWarning(object1Id, object2Id, warningLevel, distance);
}
private async void OnApplicationQuit()
{
await websocket.Close();
}
}