首页 > 解决方案 > Javascript:无法读取未定义的属性“移动”

问题描述

我的脚本中出现以下错误:player.js 第 26 行的“无法读取未定义的属性‘移动’”

不知道为什么,因为我在 userMovement.js 中定义了“this.movi​​ng = false”。它可能与我在 player.js 中的控制器有关吗?

有人可以帮我弄清楚为什么吗?提前致谢。

播放器.js:

var players = {};

class player {
  constructor(name, hasController) {
    this.pos = new position(this, 300, 300, 0, -16);
    this.img = new animator(this, this.pos, "tilesets/player", 4, 4, .2);
    if(hasController) this.controller = new userMovement(this, this.pos, this.img);

    this.properties = [
    this.pos,
    this.img
    ];
    if(hasController) this.properties.push(this.controller);
    this.name = name;
    players[name] = this;
    objects.push(this);
  }

  step() {
      if(this.name == client.socket.id) 
          client.send({
              posX: this.pos.x,
              posY: this.pos.y,
              id: client.socket.id,
              dir: this.img.realY,
              isAnimating: this.controller.moving
            }, "playerMovement");
  }
}

userMovement.js:

class userMovement {
  constructor(parent, pos, img) {
    this.parent = parent;
    this.pos = pos;
    this.img = img;

    this.pos.x = this.pos.x - (this.pos.x % 16/*32*/);
    this.pos.y = this.pos.y - (this.pos.y % 16/*32*/);

    this.speed = 3.5;
    this.target = {
        x: this.pos.x,
        y: this.pos.y
    }
    this.moving = false;
    this.keys = {
        W: 87,
        A: 65,
        S: 83,
        D: 68
    };
  }
  step() {
      if(keyIsDown(this.keys.W) && !this.moving) {
          this.img.setY(3);
          this.moving = true;
          this.target.y -= 32;
      }
      if(keyIsDown(this.keys.A) && !this.moving) {
          this.img.setY(1);
          this.moving = true;
          this.target.x -= 32;
      }
      if(keyIsDown(this.keys.S) && !this.moving) {
          this.img.setY(0);
          this.moving = true;
          this.target.y += 32;
      }
      if(keyIsDown(this.keys.D) && !this.moving) {
          this.img.setY(2);
          this.moving = true;
          this.target.x += 32;
      }
      if(this.moving) {
          var distX = this.target.x - this.pos.x;
          var distY = this.target.y - this.pos.y;
          var dx = Math.sign(distX) * this.speed;
          var dy = Math.sign(distY) * this.speed;
          if(Math.abs(distX) <= this.speed && Math.abs(distY) <= this.speed) {
              this.pos.x = this.target.x;
              this.pos.y = this.target.y;
              this.img.setX(0);
              this.moving = false;
          } else {
              this.pos.x += dx;
              this.pos.y += dy;
              this.img.animateX();
          }
      }
  }
}

标签: javascript

解决方案


if(hasController)在“player.js”中并不能确保this.controller实际启动。

检查player类被实例化的代码。也许您正在将虚假值传递给玩家构造函数?这将导致this.controller = new userMovement(this, this.pos, this.img);在 player.js 中不被执行。


推荐阅读