Search code examples
javascriptphaser-frameworkblocklygoogle-blockly

How to get blockly to see a variable's value at runtime instead of what it was when it was added


We're using blockly to control a phaser game and this is set up so that if statements can be made with custom variables from the game, e.g. the speed or direction of an element within the game.

The problem we've got is that blockly reads the values of those variables when the variables are added onto the if statement (dragged from the toolbox), instead of what they are at runtime, which may have been changed by the physics engine of the game.

For example:

var code = speed; 

This returns the value of the speed when the block was added to the code stack from the toolbox. We want it to return the value of the speed when the code is actually running.

We tried creating custom interpreters for them, but it appears that the purpose of those is just for running custom functions, not for returning custom variables.

We tried using a getter function for the variable and returning that in the definition function

Blockly.JavaScript['speed'] = function(block) {
    var code = function() {return getSpeed();}
    return [code, Blockly.JavaScript.ORDER_NONE];
};

It doesn't fire at all, the statement doesn't evaluate at all... or at least, that's what it seems like

How can we get blockly to read a variable's value at runtime?


Solution

  • If you want to to see individual values of variables or blocks you need to get first all blocks from workspace

    Blockly.mainWorkspace.getAllBlocks()
    

    Above code will return all the dropped blocks in workspace from this you can get name of your block using loop and filter the data you want to get

    var myblocks = Blockly.mainWorkspace.getAllBlocks()
    for( var i=0;i<myblocks.length; i++){
      if(myblocks[i].type == 'speed'){
        console.log(myblocks[i].getFieldValue('fieldName'));
      }
    }