Murdoc Gould
Murdoc Gould

Reputation: 33

Defining Position in Phaser

I'm making a very basic game in Javascript using the Phaser Directory. I have made games with Phaser many times before but this time I have come across an issue that is new to me and I've never had before. I've looked it up online and no one seems to have had this problem. In phaser it is telling me my "x" is not defined when I refer to x as a position. How would I go about defining x as a position or what error am I facing? I and currently using VS Code on mac with a Chrome browser and newest version of Phaser. Thanks for the Help, Murdoc

var game = new Phaser.Game(640, 360, Phaser.Auto);
var car1;

var GameState = {
  preload: function(){
    game.load.image("thecar1", "../assets/car_1.png");
    //game.load.image("thecar2", "../assets/car_2.png");
    //game.load.image("backgroundImg", "../assets/thebackground.png");
  },
  create: function(){
    var car1 = game.add.sprite(200, 270, "thecar1");
    //var car2 = game.add.sprite(200, 270, "thecar2");

    /*game.input.keyboard.addKey(Phaser.Keyboard.W)
      .onDown.add(car1Up);*/

    game.input.keyboard.addKey(Phaser.Keyboard.A)
      .onDown.add(car1Left);

    /*game.input.keyboard.addKey(Phaser.Keyboard.S)
      .onDown.add(car1Down);

    game.input.keyboard.addKey(Phaser.Keyboard.D)
      .onDown.add(car1Right);*/
  },
  update: function(){
    
  }
};

function car1Left() {

  car1.x = car1.x + 10;

}

game.state.add('GameState', GameState);
game.state.start('GameState');
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Pixel Soccer</title>

        <script src="phaser.js"></script>
        <script src="main.js"></script>
        <style>
            body {
                background: white;
                margin: 0;
                padding: 0; 
            }

            body canvas {
                margin-left: auto;
                margin-right: auto;
            }
        </style>
    </head>

    <body>
    </body>
</html>

Upvotes: 1

Views: 442

Answers (1)

Kamen Minkov
Kamen Minkov

Reputation: 3767

You're declaring the same variable twice. You're dealing with what's called "variable shadowing". When you do var car1 = game.add.sprite(200, 270, "thecar1"); in the create() function, the scope changes to function-only and the variable with the sprite you assign to it is only available in the scope of that function. The error basically comes to tell you that var car1 that you declared outside of the function scope is undefined (which it is). Try doing just car1 = game.add.sprite(200, 270, "thecar1"); inside create() and it should be fine.

Upvotes: 1

Related Questions