美文网首页
Unity LockStep

Unity LockStep

作者: unlockc | 来源:发表于2021-03-11 09:45 被阅读0次

    1、关于Update、断网重连重要代码

    原文CSDN地址 https://blog.csdn.net/FlyToCloud/article/details/104884840
    FixedUpdate帧处理

    --累计经过的时间
    local accumilateTime
    --下一次事件帧时间
    local nextKeyTime
    --事件帧间隔
    local keyLen
    --下一次逻辑帧时间
    local nextLogicTime
    --当前逻辑帧数
    local logicNum
    -逻辑帧间隔
    local logicLen
     
    --dt即为渲染帧间隔(可以和unity保持一致即60帧/s)
    function lockStep.Update(dt)
        --计算累计经过的时间
        accumilateTime = accumilateTime + dt
        --累积时间大于关键帧的时候  
        if accumilateTime >= nextKeyTime then
            --*2*.取得缓存的用户操作并处理
            --如果缓存没数据了则锁定客户端
            if noData then
                return
            end
            --更新下一个事件帧时间
            nextKeyTime = nextKeyTime + keyLen
        end
        --处理逻辑帧(这里while循环是防止某一帧间隔过大跨度了多个逻辑帧的情况)
        while(accumilateTime > nextLogicTime) do
            --*3*.执行逻辑处理
            lockStep:LogicUpdate(logicLen)
            --下一个事件帧到达前
            if nextLogicTime == nextKeyTime - logicLen then
                --*1*.向服务器请求当前用户的所有操作并缓存
            end
            --更新当前逻辑帧数和下一次逻辑帧时间
            logicNum = logicNum + 1
            nextLogicTime = nextLogicTime + logicLen
        end
        --设置渲染参数(结果为当前渲染帧在两个逻辑帧之间比值)
        renderLerpValue = (accumilateTime + logicLen - nextLogicTime) / logicLen
        --*4*.调用渲染处理将计算的插值参数传进去
        lockStep:RenderUpdate(renderLerpValue)
    end
    

    断网重连处理

    --断线重连逻辑
    function lockStep:ReLogic()
        local num = 0
        while(num < reLogicNum) do
            --到达事件帧时
            if num >= nextKeyNum then
                --取得用户操作并执行
            end
            --执行逻辑帧
            self:LogicUpdate(logicLen)
            --同步逻辑帧数
            logicNum = logicNum + 1
            --更新步骤
            num = num + 1
        end
        --同步累积时间、逻辑帧、关键帧等信息
        nextLogicTime = logicNum * logicLen
        accumilateTime = nextLogicTime
        nextKeyTime = accumilateTime + keyLen
    end
     
    --断线重连走完之后让逻辑回到正常的update即可
    

    2、Demo

    此Demo非自作,跳过去git自然知道作者。
    UnityLockStepDemo的github地址 https://github.com/yangyujiang/UnityLockStepDemo

    相关文章

      网友评论

          本文标题:Unity LockStep

          本文链接:https://www.haomeiwen.com/subject/gqsnqltx.html