示例
一个所有人共享的电梯:按钮切换上下,平台在每台客户端本地平滑移动,网络只传一个字节的”上/下”状态。
Toggle()。using UnityEngine;
using Cilbox;
using Aeloria;
using Aeloria.Network.Core;
[Cilboxable]
public class SyncedElevator : MonoBehaviour
{
public Transform platform;
public float lowY = 0f;
public float highY = 3f;
AeloriaNetworkShim net;
bool up;
float targetY;
void Start()
{
net = GetComponent<AeloriaNetworkShim>();
net.NetworkReady += OnReady;
net.NetworkMessageReceived += OnMessage;
targetY = lowY;
}
void OnDestroy()
{
if (net == null) return;
net.NetworkReady -= OnReady;
net.NetworkMessageReceived -= OnMessage;
}
void OnReady() { }
public void Toggle()
{
if (!net.HasNetworkID) return;
if (!net.IsOwnedLocallyOnServer) return;
up = !up;
targetY = up ? highY : lowY;
net.SendCustomNetworkEvent(new byte[] { up ? (byte)1 : (byte)0 }, DeliveryMethod.ReliableSequenced);
}
void OnMessage(ushort sender, byte[] buffer, DeliveryMethod method)
{
if (buffer == null || buffer.Length < 1) return;
up = buffer[0] != 0;
targetY = up ? highY : lowY;
}
void Update()
{
Vector3 p = platform.position;
float y = Mathf.MoveTowards(p.y, targetY, 2f * Time.deltaTime);
platform.position = new Vector3(p.x, y, p.z);
}
}
网络只负责”目标楼层”,平滑移动在每台机器本地做:消息量最小,而且没人会因为丢包看到瞬移。