javascript - Javascript:无法读取未定义的属性“移动”
问题描述
我的脚本中出现以下错误:player.js 第 26 行的“无法读取未定义的属性‘移动’”
不知道为什么,因为我在 userMovement.js 中定义了“this.moving = 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();
}
}
}
}
解决方案
if(hasController)
在“player.js”中并不能确保this.controller
实际启动。
检查player
类被实例化的代码。也许您正在将虚假值传递给玩家构造函数?这将导致this.controller = new userMovement(this, this.pos, this.img);
在 player.js 中不被执行。
推荐阅读
- linux-kernel - 线程中断处理程序和tasklet有什么区别?
- swift - SwiftUI - 十六进制颜色不正确
- reactjs - Angular 项目中的更改会重新加载网页,但不需要在 React 中重新加载
- ruby-on-rails - 如何在 Rspec 3.10 Rails 中获取测试环境的主机和端口配置
- reactjs - 删除模态。反应 Redux。无法读取未定义的属性“_id”
- python - 使用 anaconda 创建环境时出现冲突错误
- python - 同时从移动设备和 Web 刷新 JWT 令牌的最佳实践
- ruby-on-rails - 确保双筒名称大写
- c - 使用 C 在 Visual Studio 2019 中制作 DLL 库
- excel - Python win32com excel进程文件访问或权限问题