0

我目前正在研究 .net 中的 reactx 以用于模拟重度视频游戏。我的第一个目标是创建基本的事件/渲染循环。我有以下代码几乎完全符合我的要求。

var frames = Observable
    .Interval(TimeSpan.Zero, new EventLoopScheduler())
    .Timestamp()
    .Select(timestamp => new Frame
    {
        Count = timestamp.Value,
        Timestamp = timestamp.Timestamp.ToUnixTimeMilliseconds()
    });

frames.Subscribe(frame =>
{
    Console.WriteLine($"GameObject 1 - frame.Count: {frame.Count} frame.Timestamp: {frame.Timestamp}");
});

frames.Subscribe(frame =>
{
    Console.WriteLine($"GameObject 2 - frame.Count: {frame.Count} frame.Timestamp: {frame.Timestamp}");
});

frames.ToTask().Wait();

这会在主线程上尽快发出帧事件。完美的!但是,我注意到同一帧的两个订阅者之间的时间戳可能略有不同。例如,

GameObject 1 - frame.Count: 772 frame.Timestamp: 1519215592309
GameObject 2 - frame.Count: 772 frame.Timestamp: 1519215592310

同一帧的时间戳相差一毫秒。为此,这两个游戏对象/订阅者都需要在每帧获得完全相同的时间戳,否则模拟可能无法正常运行。

我猜 Timestamp 运营商正在为每个订阅者对流中发出的每个事件进行一次评估。有没有办法让它为每个事件发出的所有订阅者评估一次?谢谢!

4

1 回答 1

1

Whelp,我应该再给它几分钟的文档阅读时间。

解决方案是让我的帧事件流可连接。我所要做的就是在订阅者附加到它之前发布帧事件流。然后在事件循环开始之前调用 Connect。完美的!该死的Rx很棒。

var frames = Observable
    .Interval(TimeSpan.Zero, new EventLoopScheduler())
    .Timestamp()
    .Select(timestamp => new Frame
    {
        Count = timestamp.Value,
        Timestamp = timestamp.Timestamp.ToUnixTimeMilliseconds()
    })
    .Publish();

frames.Subscribe(frame =>
{
    Console.WriteLine($"GameObject 1 - frame.Count: {frame.Count} frame.Timestamp: {frame.Timestamp}");
});

frames.Subscribe(frame =>
{
    Console.WriteLine($"GameObject 2 - frame.Count: {frame.Count} frame.Timestamp: {frame.Timestamp}");
});

frames.Connect();

frames.ToTask().Wait();
于 2018-02-21T13:17:37.643 回答