Snapshot-based State Replication 基于快照的状态复制网络框架,快照同步

image

 tick system : 1秒30tick

关键帧:2秒下发一次

snapshot : 走udp发送

ghost : 需要同步的网络对象

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// TickSystem 必须在服务器和客户端都有一份
/// </summary>
public class TickSystem {
    
    private const float fixedDeltaTime = 1f / 60f; // 固定 60Hz tick,也就是1秒60tck,可以改
    private float accumulator = 0f;
    private int currentTick = 0;
    
    public void Update()
    {
        // 把真实帧率的时间累积进来
        accumulator += Time.deltaTime;

        // 当累积时间 >= 一个固定帧时,执行一次逻辑 Tick
        while (accumulator >= fixedDeltaTime)
        {
            currentTick++;
            OnTick(currentTick);  // 调用游戏逻辑 (网络同步、物理预测等)
            accumulator -= fixedDeltaTime;
        }

        // 插值比例(当前帧在两个 tick 之间的百分比)
        float alpha = accumulator / fixedDeltaTime;
        OnRender(alpha); // 用来做快照插值渲染
    }
    
    // tick的频率是固定的,tickId是递增的
    void OnTick(int tickId)
    {
        // 逻辑帧执行内容,比如:
        // - 收发网络消息
        // - 处理预测 & 回滚
        // - 更新游戏状态
        
    }
    
    
    // 用来做快照插值渲染,只有客户端有
    void OnRender(float alpha)
    {
        // 渲染用:alpha ∈ [0,1)
        // - 插值前后两个 tick 的快照
        // - 平滑显示,而不是卡顿
        
    }
}

 

posted @ 2025-09-09 22:09  三页菌  阅读(3)  评论(0)    收藏  举报