[英]Does it make sense to use Web Workers for a game?
I am working on a game that has AI logic, movement, etc and drawing. 我正在开发一款具有AI逻辑,动作等和绘图的游戏。 Does it make sense to calculate moving and AI logic using Web Workers? 使用Web Workers计算移动和AI逻辑是否有意义? 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? 我知道有一个postMessage()系统,但感觉如此......嗯,痛苦?
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. 它几乎需要对该对象的整个访问。
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. 我认为将WebWorkers用于游戏确实有意义,但是,这意味着你必须保留一个游戏状态对象,该对象可以转换为有效的JSON,你可以传递给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) 然后你为巡逻和可能的事件设置了一个webworker(你可以调用webworker中的其他webworkers并处理巡逻事件)
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. 现在必须清楚的是,使用WebWorkers实际上是一个架构决策,如果你想使用它们,它将涉及大量的重构。 Without the refactoring, I doubt it's useful for you at all. 没有重构,我怀疑它对你有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.