unity 自制socket联机 卡顿的解决

最近再写客户端的网络联机,刚开始就是简单的发送接收,看上去非常卡顿。

 

于是做了一个平滑的处理,利用Vector3.lerp插值处理,设置一个缓冲list,堆积操作数量多时,加速处理。数量少时正常处理。

 

贴一下代码,Set Animation代码和这个无关,就不贴了。

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Team7.Network;

public class otherPlayer_script : MonoBehaviour {


    private List PosList = new List();
    NetworkManager networkMgr = NetworkManager.GetInstance();

    float lerpSpeed;
    float normalSpeed = 20f;
    float fastSpeed = 30f;
    float closeEnough = 0.05f;

    Vector3 position;
    string keyCode;
	// 这个角色只需要监听即可
	void Start () {
        networkMgr.m_CActor._messageContributionMgr.AddPlayerListener(nameof(mmopb.m_positon), GetMovementInfoCb);
        networkMgr.m_CActor._messageContributionMgr.AddPlayerListener(nameof(mmopb.m_keycode), GetKeyInfoCb);
        lerpSpeed = normalSpeed;
    }
    private void Update()
    {
        Lerping();
    }
    //平滑插值
    void Lerping()
    {
        if (PosList.Count > 0)
        {
            this.transform.position = Vector3.Lerp(this.transform.position, PosList[0], Time.deltaTime * lerpSpeed);

            if (Vector3.Distance(this.transform.position, PosList[0]) < closeEnough)
            {
                PosList.RemoveAt(0);
            }

            if (PosList.Count > 10)
            {
                lerpSpeed = fastSpeed;
            }
            else
            {
                lerpSpeed = normalSpeed;
            }
        }
    }
    //接收监听
    void GetMovementInfoCb(object msg)
    {
        Debug.Log("get success");
        if (msg is mmopb.m_positon)
        {
            var o = msg as mmopb.m_positon;
            position.x = o.pos.x;
            position.y = o.pos.y;
            position.z = o.pos.z;

            Debug.Log("Get Success");

            PosList.Add(position);
            //this.gameObject.transform.position = position;
        }
    }
    
    void GetKeyInfoCb(object msg)
    {
        if(msg is mmopb.m_keycode)
        {
            var o = msg as mmopb.m_keycode;

            keyCode = o.key;

            SetAnimation();
        }
    }
}

 

你可能感兴趣的:(unity 自制socket联机 卡顿的解决)