HI, i’m trying to implement Workers in my game, i’ve already tested a simple example on a simple AS3 project it’s working great, but once i tried the same thing on my Main class on FlashPunk, i get no response from my worker :
[Frame(factoryClass = "Preloader")]
public class Main extends Engine
{
protected var mainToWorker:MessageChannel;
protected var workerToMain:MessageChannel;
protected var worker:Worker;
public function Main():void
{
super(900, 600, 60, false);
Text.font = "Snig";
}
override public function init():void
{
if(Worker.current.isPrimordial){
//Create worker from our own loaderInfo.bytes
worker = WorkerDomain.current.createWorker(this.loaderInfo.bytes);
//Create messaging channels for 2-way messaging
mainToWorker = Worker.current.createMessageChannel(worker);
workerToMain = worker.createMessageChannel(Worker.current);
//Inject messaging channels as a shared property
worker.setSharedProperty("mainToWorker", mainToWorker);
worker.setSharedProperty("workerToMain", workerToMain);
//Listen to the response from Worker
workerToMain.addEventListener(Event.CHANNEL_MESSAGE, onWorkerToMain);
//Start worker (re-run document class)
worker.start();
//Set an interval that will ask the worker thread to do some math
setInterval(function(){
mainToWorker.send("HELLO");
trace("[Main] HELLO");
}, 1000);
}
/**
* Start Worker thread
**/
else {
//Inside of our worker, we can use static methods to
//access the shared messgaeChannel's
mainToWorker = Worker.current.getSharedProperty("mainToWorker");
workerToMain = Worker.current.getSharedProperty("workerToMain");
//Listen for messages from Main
mainToWorker.addEventListener(Event.CHANNEL_MESSAGE, onMainToWorker);
}
super.init();
}
protected function onMainToWorker(event:Event):void {
var msg:* = mainToWorker.receive();
//When the main thread sends us HELLO, we'll send it back WORLD
if (msg == "HELLO") {
workerToMain.send("WORLD");
}
}
//Receive messages FROM the Worker
protected function onWorkerToMain(event:Event):void {
//Trace out whatever message the worker has sent us.
trace("[Worker] " + workerToMain.receive());
}
}