kittykatattack / hexi

Make games the fun way!
MIT License
551 stars 83 forks source link

Global variable undefined #42

Open eliasfeijo opened 6 years ago

eliasfeijo commented 6 years ago

The tutorials and examples work fine, but I'm having issues with my own code.

If I declare the global variables after g.start() (like the tutorial), they get overwritten after that method to undefined, by their own declaration. And I can't access their value on the play method. Example:

let g = hexi(512, 512, setup);
g.scaleToWindow();
g.start();

let player, gameScene;

function setup(){
        gameScene = g.group();
        player = g.rectangle(48, 48, "blue");
        player.x = g.canvas.width  / 2 - player.halfWidth;
        player.y = g.canvas.height / 2 - player.halfHeight;
        gameScene.addChild(player);
        g.state = play;
}

function play(){
        console.log("player: ", player);
        // outputs 'player: undefined'
}

Looks like the g.start() calls the setup function before I declare the global variables, and when it's done, it goes back into the declaration block let player, gameScene;, setting them to undefined. I confirmed this using browser debugging tool.

So my workaround is to declare the global variables before g.start(), and it works fine for now. But something is smelly here, why the tutorials and example works, and my own code doesn't?

I already tried different setups, separated hexi modules and core, changed babel preset, but still no success. It gave me a serious headache, I had to submit this issue.

kittykatattack commented 6 years ago

@eliasfeijo Thanks for posting this! Yes, I found exactly the same problem in a few of my own projects. And, like you, it seems the solution is declare your global application variables before start.