Tuesday, 15 May 2012

asynchronous - Using C# 5 async to wait for something that executes over a number of game frames -



asynchronous - Using C# 5 async to wait for something that executes over a number of game frames -

my boy writing simple rpg game has number of non-player characters (aka npc's). each npc has associated "script" controls behaviour. going utilize mini custom script language write these behaviours i'm wondering if improve done in c#5/async.

taking simple example, suppose 1 of npc's walks between 2 points i'm thinking nice write this:

while (true) { await walkto(100,100); await walkto(200,200); }

the walkto method async method handles walking between 2 points , on number of frames game loop. it's not blocking method can off-loaded background thread.

and i'm stuck... haven't been able find examples using async/await in manner, seems perfect it.

ideas?

here's rough pseudo code i'd do:

class npcbase { // called game loop public void onupdate(double elapsedtime) { // move npc . . . // arrived @ destination? if (arrived) { // how trigger task finished? _currenttask.markcomplete(); } } // async method called npc "script" public async task walkto(int x, int y) { // store new target location // homecoming task object "triggered" when walk finished _currenttask = <something??> homecoming _currenttask; } task _currenttask; }

okay, sounds 1 alternative have taskcompletionsource each frame of game. can await task walkto, , set result in onupdate:

private taskcompletionsource<double> currentframesource; // called game loop public void onupdate(double elapsedtime) { ... var previousframesource = currentframesource; currentframesource = new taskcompletionsource<double>(); // trigger continuations... previousframesource.setresult(elapsedtime); } // async method called 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 } }

i'm not sure how efficient be, admittedly... should work.

c# asynchronous c#-5.0

No comments:

Post a Comment