书接上文,有了一个基本的网络同步消息的服务器,客户端这边其实要做的工作就简单许多。
如果对位置信息的保密程度没那么高的话,可以放在客户端处理这部分的逻辑。
即一个客户端移动的时候,另一个客户端跟着移动,基本代码如下:
using Coldairarrow.Util.Sockets;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyClient : MonoBehaviour
{
private SocketClient client;
public Transform obj;
//public Transform obj2;
//public string test = "hellow222";
private MoveObj mo = new MoveObj();
public string str = "";
// Start is called before the first frame update
void Start()
{
client = new SocketClient();
client.StartClient();
//client.Send(test);
client.HandleRecMsg = new Action<string, SocketClient>((_str, _client) =>
{
Debug.Log(_str);
str = _str;
//var _s = JsonUtility.FromJson<MoveObj>(_str);
//obj.transform.position = _s.p;
//obj.transform.rotation = Quaternion.Euler(_s.r);
});
mo.name = obj.name;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
obj.transform.Translate(Vector3.forward * 0.3f);
mo.p = obj.transform.position;
mo.r = obj.transform.rotation.eulerAngles;
client.Send(JsonUtility.ToJson(mo));
}
if (!string.IsNullOrEmpty(str))
{
var _s = JsonUtility.FromJson<MoveObj>(str);
obj.transform.position = _s.p;
obj.transform.rotation = Quaternion.Euler(_s.r);
}
}
}
[Serializable]
public class MoveObj
{
public Vector3 p;
public Vector3 r;
public string name;
}
测试结果: