views:

38

answers:

1

Hi,

I am working on a game that has AI logic, movement, etc and drawing. Does it make sense to calculate moving and AI logic using Web Workers? But how do I do that -- because the workers need to know so much about the main thread like the positions of certain objects for collisions, amount of bullets, etc. It feels like impossible because the worker is completely separate from the main thread with no access what so ever. I do know that there a postMessage() system, but that feels so ... umm, painful?

For example, I have a rifleman object that represents a rifleman with a sprite, position, health, etc. I want him to patrol. So, how do I do that patrolling code on a worker? It would need pretty much the whole access to that object.

+1  A: 

I think it does make sense to use WebWorkers for a game, but yeah, it will mean you will have to keep a game state object which can be converted to valid JSON which you can pass to webworkers. On the brightside, you can also put a lot of intrinsic data inside those webworkers as well.

var gameState = {
   sprites: {
      {
         type: 'rifleman',  // damage, accuracy, speed etc set inside appropriate webworker.
         owner: 'playerA', 
         x: 100,
         y: 100,
         z: 0,
         level: 1, // used to fetch modifiers to dmg, acc, speed etc.

      },
      {
         // each sprite it's own state obj.
      }
   }
}

then you set up a webworker for patrolling and possible events (you can call other webworkers inside a webworker as well and process patrol events)

var patrolWorker = new WebWorker('patrolWorker');
patrolWorker.onmessage = function(e){
   render(e.data); // your render function, can ALSO be a webworker if you like ;)
}
patrolWorker.postMessage(gameState.sprites);

It must become clear by now, that using WebWorkers is actually very much an architectural decision, if you want to use them, it will involve a lot of refactoring. Without the refactoring, I doubt it's useful for you at all.

BGerrissen