Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

170
Visualizações
player object undefined only in update()ƒ

not exactly sure what to call whats going on. I need to create a definition for the clients main player physics body and i can't read it or any of its properties, no matter where or how i call it, from update(). Also if this is a bit hard to understand Im a young and new JS programmer so bare with me. Im willing to change the construction of my scenes if i need to if anyone recommends something easier.


    class MainScene extends Phaser.Scene {
    constructor() {
      super({ key: 'MainScene' })
    }

    preload() {
        this.load.image('grass','./assets/map.png',);
        this.load.spritesheet('graf', './assets/wang.png', { frameWidth: 200, frameHeight: 170})
      }
    
    create() {
      this.add.image(100,400,'grass');
      this.playerMap = {};
      Client.askNewPlayer();
      window.myScene = this;
      this.body  = this.matter.bodies.circle(
          1,
          1,
          10,
          {
              isSensor: true
          }
          );
    }
    addNewPlayer(id, x, y) {
        if(id == clientID){
            this.playerMap[id] = this.matter.add.sprite(x, y, 'graf','', {'shape' : this.body['player-20-00']}).setScale(.5);
            this.player = this.playerMap[id];
            this.cameras.main.centerOn(this.player.x, this.player.y)
        }
        else{
        this.playerMap[id] = this.add.sprite(x,y,'graf').setScale(.5);
        }
    }
    removePlayer(id){
        this.playerMap[id].destroy();
    delete this.playerMap[id];
    }
    movePlayer(id, x, y) {       
        // var player = this.playerMap[id];
        // var distance = Phaser.Math.Distance.Between(player.x,player.y,x,y);
        // var duration = distance*10;
        // var tween = this.add.tween(player);
        // tween.to({x:x,y:y}, duration);
        // tween.start();
        
    }
  
    update(){
       //haven't been able to access any variables Ive called from here
       this.cameras.main.centerOn(this.player.x, this.player.y)//causes error "can't read properties of undefined"
//replacing this.player.y or y with playerMap[a].x or y doesn't work either even though its accessible from everywhere else and === (equivalent) 
    }
}

here is the client object, I'm pretty sure this doesn't affect my problem

var Client = {};
var clientID;
Client.socket = io.connect();
Client.askNewPlayer = function(){
    Client.socket.emit('newplayer');
}
Client.socket.on('newplayer',function(data){
    window.myScene.addNewPlayer(data.id,data.x,data.y);
});

Client.socket.on('allplayers',function(data){
    console.log(data);
    for(var i = 0; i < data.length; i++){
        window.myScene.addNewPlayer(data[i].id,data[i].x,data[i].y);
    }
});

Client.socket.on('remove',function(id){
    window.myScene.removePlayer(id);
});
Client.socket.on('move',function(data){
    window.myScene.movePlayer(data.id,data.x,data.y);
});
Client.socket.on('id',function(id){
    clientID = id;
})

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The issue is, that the update function is called, before a player is added ( aka before the this.player is set).

Since the update function will fire more or less right after the create function, the property player of the scene is not set yet. So this.player is undefined, which is the cause for the the error.

The solution is to check, if the this.player property is set before accessing it, in the update function.

As soon as the this.player property is set, the other commands in the if - clause are called.

update(){
    if(this.player){
      this.cameras.main.centerOn(this.player.x, this.player.y);
      // ...
    }
}

or like this, it is a bit better to read (following the "Return Early Pattern" ):

update(){
    if(!this.player){
        return ;
    }
    this.cameras.main.centerOn(this.player.x, this.player.y);
    // ...
 }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda