# 同步与网络 ## Y3多人同步架构 Y3引擎采用**确定性锁步同步**,核心原则:所有影响游戏逻辑的代码必须在所有客户端产生一致结果。 --- ## Timer vs LocalTimer vs ClientTimer | 类型 | 模块 | 同步性 | 用途 | |------|------|--------|------| | `y3.timer` (Timer) | `Timer` | **同步** | 游戏逻辑、伤害、移动、状态判定 | | `y3.ltimer` (LocalTimer) | `LocalTimer` | 本地 | UI动画、特效延迟、提示文字 | | `y3.ctimer` (ClientTimer) | `ClientTimer` | 本地 | 客户端帧级计时 | ### 黄金法则 > 任何改变游戏状态的逻辑(单位属性、伤害、Buff、死亡、积分等)**必须使用 `y3.timer`**。 > 仅影响视觉呈现的(粒子、UI文字、音效淡入)可用 `y3.ltimer` 或 `y3.ctimer`。 ```lua -- 正确:刺杀前摇用同步计时器 y3.timer.wait(0.5, function() attacker:damage({ target = target, damage = 70 }) end) -- 错误:用本地计时器处理伤害(各客户端时机不同,会导致不同步) -- y3.ltimer.wait(0.5, function() -- attacker:damage(...) -- end) ``` --- ## Player.with_local `Player.with_local()` 在本地玩家上下文执行代码,典型用于UI更新: ```lua -- 只在对应玩家的客户端显示HUD y3.player.with_local(function(local_player) -- local_player就是当前客户端对应的Player local unit = local_player:get_selecting_unit() if unit then local sus = unit:storage_get('suspicion') or 0 -- 更新UI显示 end end) ``` **在 with_local 中不可执行的操作**: - `unit:damage()` — 会导致各端伤害次数不同 - `unit:add_buff()` — Buff应在同步代码中添加