我儿子正在编写一个简单的 RPG 游戏,其中有许多非玩家角色(又名 NPC)。每个 NPC 都有一个相关的“脚本”来控制其行为。我们将使用迷你自定义脚本语言来编写这些行为,但我现在想知道在 C#5/Async 中是否会更好。
举一个非常简单的例子,假设其中一个 NPC 只是在两点之间行走,我想写这样的东西会很好:
while (true)
{
await WalkTo(100,100);
await WalkTo(200,200);
}
WalkTo 方法是一个异步方法,它处理与在两点之间行走有关的所有事情,并在游戏循环中的多个帧上执行此操作。它不是一种可以卸载到后台线程的阻塞方法。
这就是我陷入困境的地方......我还没有找到任何以这种方式使用 async/await 的例子,但它似乎是完美的。
Ideas?
这是我想做的一些非常粗略的伪代码:
class NpcBase
{
// Called from game loop
public void onUpdate(double elapsedTime)
{
// Move the NPC
.
.
.
// Arrived at destination?
if (Arrived)
{
// How do I trigger that the task is finished?
_currentTask.MarkComplete();
}
}
// Async method called by NPC "script"
public async Task WalkTo(int x, int y)
{
// Store new target location
// return a task object that will be "triggered" when the walk is finished
_currentTask = <something??>
return _currentTask;
}
Task _currentTask;
}
好吧,听起来一个选择是TaskCompletionSource http://msdn.microsoft.com/en-us/library/dd449174.aspx对于游戏的每一帧。然后您可以等待Task http://msdn.microsoft.com/en-us/library/dd449187.aspx from WalkTo
,并将结果设置为OnUpdate
:
private TaskCompletionSource<double> currentFrameSource;
// Called from game loop
public void OnUpdate(double elapsedTime)
{
...
var previousFrameSource = currentFrameSource;
currentFrameSource = new TaskCompletionSource<double>();
// This will trigger all the continuations...
previousFrameSource.SetResult(elapsedTime);
}
// Async method called by NPC "script"
public async Task WalkTo(int x, int y)
{
// Store new target location
while (/* we're not there yet */)
{
double currentTime = await currentFrameSource.Task;
// Move
}
}
诚然,我不确定这会有多有效……但它应该有效。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)