Jump to content

game.js:56 Uncaught TypeError: Cannot read property 'body' of undefined


KnTproject
 Share

Recommended Posts

Hello,

 var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update });
        var cursors;
        var cookie;
 
        function preload () {
        game.load.image('cookie','Assets/cookie.png');
        
        }

        function create () {

        game.add.image(0,0,'cookie'); 
        cursors = game.input.keyboard.createCursorKeys();
        game.physics.arcade.enable(cookie);

        }


      function update() {

        cookie.body.velocity.x = 0;
      
         if (cursors.right.isDown){
             cookie.body.velocity.x = +10;
           }

         }
 

This is my whole code. Now I want to move the cookie, but the whole time I get this ERROR;

game.js:56 Uncaught TypeError: Cannot read property 'body' of undefined

Do anybody knows a solution?

Link to comment
Share on other sites

What douglas said is right, because you can't enable body to an image you should use a sprite.

But you can move the cookie if it's an image without enabling body by replacing this:

 function update() {

        cookie.body.velocity.x = 0;
      
         if (cursors.right.isDown){
             cookie.body.velocity.x = +10;
           }

  }

With this:

 function update() {
         if (cursors.right.isDown){
             cookie.x += 2;
           }

  }

:)

Link to comment
Share on other sites

Nope, try again guys ;)

From the code snippet and the error message its just that cookie is never defined, its declared but thats it. It is in scope at least, its just you never assign the variable to any object.

In the preload you add an image to a stack and inside create it looks like you add it to another stack, but they are internal stacks to Phaser, which I'm guessing you probably reference by string or maybe you can grab the stack somehow, in either case, you never assign it to the variable 'cookie' you declared earlier, hence, when you try and access body (and then velocity and x) you get the error.

Reread the error report, its concise but its all the info you need at the moment.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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