简短的回答是肯定的,可以完成您正在寻找的关于游戏更新循环解耦的内容。我使用 Rx 和 XNA 创建了一个概念验证,它使用了一个与游戏循环没有任何关联的渲染对象。相反,实体会触发一个事件来通知订阅者他们已准备好进行渲染;事件数据的有效负载包含当时为该对象渲染帧所需的所有信息。
渲染请求事件流与计时器事件流(只是一个Observable.Interval
计时器)合并,以使渲染与帧速率同步。它似乎工作得很好,我正在考虑在更大的范围内对其进行测试。对于批量渲染(一次多个精灵)和单独渲染,我已经让它看起来工作得很好。请注意,以下代码使用的 Rx 版本是 WP7 ROM (Mirosoft.Phone.Reactive) 附带的版本。
假设你有一个类似这样的对象:
public abstract class SomeEntity
{
/* members omitted for brevity */
IList _eventHandlers = new List<object>();
public void AddHandlerWithSubscription<T, TType>(IObservable<T> observable,
Func<TType, Action<T>> handlerSelector)
where TType: SomeEntity
{
var handler = handlerSelector((TType)this);
observable.Subscribe(observable, eventHandler);
}
public void AddHandler<T>(Action<T> eventHandler) where T : class
{
var subj = Observer.Create(eventHandler);
AddHandler(subj);
}
protected void AddHandler<T>(IObserver<T> handler) where T : class
{
if (handler == null)
return;
_eventHandlers.Add(handler);
}
/// <summary>
/// Changes internal rendering state for the object, then raises the Render event
/// informing subscribers that this object needs rendering)
/// </summary>
/// <param name="rendering">Rendering parameters</param>
protected virtual void OnRender(PreRendering rendering)
{
var renderArgs = new Rendering
{
SpriteEffects = this.SpriteEffects = rendering.SpriteEffects,
Rotation = this.Rotation = rendering.Rotation.GetValueOrDefault(this.Rotation),
RenderTransform = this.Transform = rendering.RenderTransform.GetValueOrDefault(this.Transform),
Depth = this.DrawOrder = rendering.Depth,
RenderColor = this.Color = rendering.RenderColor,
Position = this.Position,
Texture = this.Texture,
Scale = this.Scale,
Size = this.DrawSize,
Origin = this.TextureCenter,
When = rendering.When
};
RaiseEvent(Event.Create(this, renderArgs));
}
/// <summary>
/// Extracts a render data object from the internal state of the object
/// </summary>
/// <returns>Parameter object representing current internal state pertaining to rendering</returns>
private PreRendering GetRenderData()
{
var args = new PreRendering
{
Origin = this.TextureCenter,
Rotation = this.Rotation,
RenderTransform = this.Transform,
SpriteEffects = this.SpriteEffects,
RenderColor = Color.White,
Depth = this.DrawOrder,
Size = this.DrawSize,
Scale = this.Scale
};
return args;
}
请注意,此对象没有描述任何如何呈现自身,而只是充当将在呈现中使用的数据的发布者。它通过将 Actions 订阅到 observables 来公开这一点。
鉴于此,我们还可以有一个独立的RenderHandler
:
public class RenderHandler : IObserver<IEvent<Rendering>>
{
private readonly SpriteBatch _spriteBatch;
private readonly IList<IEvent<Rendering>> _renderBuffer = new List<IEvent<Rendering>>();
private Game _game;
public RenderHandler(Game game)
{
_game = game;
this._spriteBatch = new SpriteBatch(game.GraphicsDevice);
}
public void OnNext(IEvent<Rendering> value)
{
_renderBuffer.Add(value);
if ((value.EventArgs.When.ElapsedGameTime >= _game.TargetElapsedTime))
{
OnRender(_renderBuffer);
_renderBuffer.Clear();
}
}
private void OnRender(IEnumerable<IEvent<Rendering>> obj)
{
var renderBatches = obj.GroupBy(x => x.EventArgs.Depth)
.OrderBy(x => x.Key).ToList(); // TODO: profile if.ToList() is needed
foreach (var renderBatch in renderBatches)
{
_spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
foreach (var @event in renderBatch)
{
OnRender(@event.EventArgs);
}
_spriteBatch.End();
}
}
private void OnRender(Rendering draw)
{
_spriteBatch.Draw(
draw.Texture,
draw.Position,
null,
draw.RenderColor,
draw.Rotation ?? 0f,
draw.Origin ?? Vector2.Zero,
draw.Scale,
draw.SpriteEffects,
0);
}
注意对事件数据进行批处理和绘制的重载 OnRender 方法Rendering
(它更像是一条消息,但不需要太语义化!)
在游戏类中连接渲染行为只需两行代码:
entity.AddHandlerWithSubscription<FrameTicked, TexturedEntity>(
_drawTimer.Select(y => new FrameTicked(y)),
x => x.RaiseEvent);
entity.AddHandler<IEvent<Rendering>>(_renderHandler.OnNext);
在实体实际渲染之前要做的最后一件事是连接一个计时器,该计时器将用作游戏各个实体的同步信标。这就是我认为的 Rx 相当于灯塔每 1/30 秒脉冲一次(默认为 30Hz WP7 刷新率)。
在你的游戏课上:
private readonly ISubject<GameTime> _drawTimer =
new BehaviorSubject<GameTime>(new GameTime());
// ... //
public override Draw(GameTime gameTime)
{
_drawTimer.OnNext(gameTime);
}
现在,使用Game
'sDraw
方法可能看似违背了目的,所以如果你宁愿避免这样做,你可以改为Publish
这样的ConnectedObservable
(Hot observable):
IConnectableObservable<FrameTick> _drawTimer = Observable
.Interval(TargetElapsedTime)
.Publish();
//...//
_drawTimer.Connect();
这种技术在 Silverlight 托管的 XNA 游戏中非常有用。在 SL 中,该Game
对象不可用,开发人员需要进行一些检查才能使传统的游戏循环正常工作。使用 Rx 和这种方法,没有必要这样做,承诺将游戏从纯 XNA 移植到 XNA+SL 的破坏性体验要小得多