CSNC/Client/Unity/CSNC.cs

118 lines
3.3 KiB
C#

using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class CSNC : MonoBehaviour
{
public float tickInterval = 5f; // x times per sec
public string ip;
public GameObjectManager manager;
private float lastPing = 0; //last time connected to server
public class EZtransform //ez consistent serialization of transforms
{
public List<float> position;
public List<float> rotation;
public EZtransform(Transform transform)
{
position = new List<float>(3);
rotation = new List<float>(4);
position.Add(transform.position.x);
position.Add(transform.position.y);
position.Add(transform.position.z);
rotation.Add(transform.rotation.x);
rotation.Add(transform.rotation.y);
rotation.Add(transform.rotation.z);
rotation.Add(transform.rotation.w);
}
public EZtransform()
{
position = new List<float>();
rotation = new List<float>();
}
}
public class CSNCObject
{
public string id;
public string type;
public EZtransform transform;
public CSNCObject()
{
id = "";
type = "";
transform = new EZtransform();
}
public CSNCObject(string type, Transform trans, string id)
{
this.id = id;
this.type = type;
this.transform = new EZtransform(trans);
}
public CSNCObject(string type, EZtransform trans, string id)
{
this.id = id;
this.type = type;
this.transform = trans;
}
}
public class SendData
{
public string uuid;
public List<CSNCObject> gameObjects;
public SendData(List<CSNCObject> gameobjects)
{
uuid = GameObjectRegistry.instance.uuid;
gameObjects = gameobjects;
}
}
void Start()
{
ip = CHANGEME; //CHANGE THIS VALUE to the ip address
}
void FixedUpdate()
{
if (Time.timeSinceLevelLoad - (1000f / tickInterval) > lastPing)
{
lastPing = Time.timeSinceLevelLoad;
IEnumerator req = request();
StartCoroutine(req);
}
}
IEnumerator request()
{
//Debug.Log(GameObjectRegistry.instance.registeredObjects);
List<CSNCObject> gameObjects = new List<CSNCObject>();
foreach (SyncData obj in GameObjectRegistry.instance.registeredObjects)
{
gameObjects.Add(new CSNCObject(obj.type, obj.transform, obj.id));
}
SendData sendData = new SendData(gameObjects);
//Debug.Log(JsonConvert.SerializeObject(sendData));
using (UnityWebRequest req = UnityWebRequest.Post(ip, JsonConvert.SerializeObject(sendData), "application/json"))
{
req.SetRequestHeader("request-type", "csnc");
yield return req.SendWebRequest();
if (req.result != UnityWebRequest.Result.Success)
{
Debug.LogError(req.error);
}
else
{
manager.SyncObjects(JsonConvert.DeserializeObject<GameObjectManager.RecievedData>(req.downloadHandler.text));
}
}
}
}