Jump to content

Uncaught ReferenceError: game is not defined


DegGa
 Share

Recommended Posts

Hello people!

I dont know what's wrong with my code, but each time i run it the console log: Uncaught ReferenceError: game is not defined

index.html:

Quote

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>testing</title>
        <script src="phaser.min.js"></script>
        <script src="load.js"></script>
        <script src="play.js"></script>
        <script src="player.js"></script>
    </head>
    <body>

    <script type="text/javascript">
        
        window.onload = function () {
            
            var game = new Phaser.Game(640, 480, Phaser.AUTO, '');


            game.state.add('load', Game.Load);
            game.state.add('play', Game.Play);

            game.state.start('load');

        }

    </script>

    </body>
</html>

load.js:

Quote

var Game = {};

Game.Load = function() {};

Game.Load.prototype = {

    preload: function() {

        this.load.image('player', "assets/player.png");

    },

    create: function() {

        this.state.start('play');

    }

};

play.js:

Quote

Game.Play = function () {};

Game.Play.prototype = {

    create: function() {

        player.create();

    },

    update: function() {

    }

};

player.js:

Quote

function Player() {

};

Player.prototype.create =  function() {

        this.player = game.add.sprite(0, 0, 'player');

};

var player = new Player();

 

Link to comment
Share on other sites

`game` is a local variable, local to the onload function.

When you call `game.add.sprite` later (in the Player class you're trying to use) there is no local `game` so the engine will look for it globally, but there is no global reference, hence the reference error.

Removing the onload closure would punt it to global, or you could do that explicitly within the function using `window.game = game` (which is an anti-pattern). You actually do expose 2 globals, namely `Game` and `player`, during the those script loads.

As an added bonus for 6 there is also the issue that your wrapping onload function is totally extraneous as, currently at least, there is no more stuff to load so that script will execute only just before the onload event is triggered (possibly in the same tick as its the last thing, it can be a little tricky to tell cross-platform).

Link to comment
Share on other sites

the thread you linked is very interesting, while i am reading it perhaps an image is better then many words

so, i am also studying anther manner then the stages froms solarus-games.org and the image that inspire me for using "this" as a delta is this one

zelda quest plus i am not sure it's sufficiant to have a correct idea of the problem

btw, i am reading the thread mentioned

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...