How to connect blockly and phaser game engine

436 views
Skip to first unread message

sean Z

unread,
Sep 30, 2017, 1:12:47 AM9/30/17
to Blockly
Dear Friends:

       I am trying to do a game and controlling by google blockly. however, I don't how to call JS code (blockly generated) in phase, perhaps a kind of callback ? or other way to solve my problem. anyone has good solution or reference could help me ?

thank you!

Andrew n marshall

unread,
Oct 1, 2017, 12:09:23 PM10/1/17
to blo...@googlegroups.com
Hi Sean,

Yes, I think a callback is the right approach. You would start with some sort of top-level block (next- or statement-block connection only). See the following example from Gamefroot:


When you make the block with the Developer Tools, you're going to see a "Generator Stub" in the lower left.  This function builds a string that contains the block's code.  In the case of an event, we want to output a function definition. That is, something like:


Blockly.JavaScript['event_level_start'] = function(block) {

 var statements_do = Blockly.JavaScript.statementToCode(block, 'DO');

 return "var whenLevelStarts = function() {\n" + statements_do + "\n};";

};


When you call Blockly.JavaScript.workspaceToCode(workspace), you will have one or more function definitions (you will need to make sure the function names are unique). These can be called from your Phaser callbacks:

function preload() {

 // Load game

// . . .


 // Call Blockly event, if defined.

 If (whenLevelStarts) {

   whenLevelStarts();

 }

}



This above code assumes the naive setup of eval()ing the workspace code. It is a quick way to get up and running, but it has security issues. Our docs on Generating and Running Javascript provide details, including how to use JS Interpreter to avoid eval().







--
You received this message because you are subscribed to the Google Groups "Blockly" group.
To unsubscribe from this group and stop receiving emails from it, send an email to blockly+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

sean Z

unread,
Oct 3, 2017, 5:30:56 AM10/3/17
to Blockly
Andrew. thank you for helping me. I will try it your way. 
To unsubscribe from this group and stop receiving emails from it, send an email to blockly+u...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages