Cannot read properties of undefined (reading 'setVelocityY'), but object is defined in one of if branches

Hi all. I am new to game making and also to phaser.io.

I am trying to make multiplayer foosball game using socket.io. I am getting information from this tutorial mostly. Here is my code:
GitHub - pali08/foosball_in_phaser_multiplayer

The problem occurs in game.js file in function handleKeyboardInput in second else if branch (line 123):

else if (cursorsUp.isUp) {
      console.log(typeof(players) == null)
      console.log(typeof(players))
      players.setVelocityY(0);
}

I want group of players to move when I press the button, but stop moving when key is released. For some reason I get

game.js:126 Uncaught TypeError: Cannot read properties of undefined (reading 'setVelocityY')
    at handleKeyboardInput (game.js:126:15)
    at initialize.update (game.js:67:3)
    at initialize.step (phaser.min.js:1:225442)
    at initialize.update (phaser.min.js:1:490723)
    at initialize.step (phaser.min.js:1:793006)
    at initialize.step (phaser.min.js:1:433503)
    at t (phaser.min.js:1:434427)

when executing game. The black background appears without players

The strange thing is, that

  • first two (if and else if) branches works correctly - player moves up and down (but does not stop when key is released)
  • If I remove content of else if (cursorsUp.isUp), program is executable, but last else if branch:
else if (cursorsDown.isUp) {
       players.setVelocityY(0);
   }

does not work. When down arrow is released, players doesn’t stop.

Any idea, where problem might be?

cursors = this.input.keyboard.createCursorKeys();

Move this to scene create(), and add

let cursors;

at the top.

currentPlayers is undefined until the 'currentGamer' event listener is called, but update() starts running before that.