javascript - 我的方法和函数在数组数组中不起作用
问题描述
我有一个二维数组,它是一个游戏板。我创建了一些对象玩家、武器等,它们也保存在自己的阵列中。到目前为止,这很好。我可以创建对象更新它们的属性等。
我现在正在尝试为游戏创建一些方法和功能。例如; 玩家拿起武器并更新属性以显示这一点。
我已经在一个数组中尝试了这些方法并且它工作了,只要我把它做成一个或多个数组,我就遇到了麻烦。
class Player {
constructor(name, players, hp) {
this.name = name;
this.players = players;
this.hp = 100;
this.currentWeapon = null;
}
pickUp(weapons) {
this.currentWeapon = weapons;
weapons.hold = true;
weapons.player = this;
}
dropOff(weapon) {
this.currentWeapon = null;
weapon.hold = false;
weapon.player = null;
}
class Weapon {
constructor(name, id, damage, weapons) {
this.name = name;
this.id = id;
this.damage = damage;
this.weapons = weapons;
this.player = null;
this.hold = false;
}
}
players.pickUp(weapons);
players.dropOff(weapons);
我基本上希望在调用函数时更新 currentWeapon 以及 this.player 和 this.hold 属性。
我也将每个类都存储为它们自己的数组。
当我运行它时,它要么说 XXX 不是函数,要么没有定义 XXX。
玩家和武器都在一个阵列的阵列上,即棋盘。
任何想法,将不胜感激!
谢谢!
解决方案
我有根据的猜测是在你的代码中的某个地方你有类似的东西:
const players = []
players.push(new Player(...)) // in a for loop
如果是这种情况,并且您希望一系列玩家有一个方法pickUp,那就是您的问题。
每个玩家对象都有一个拾取方法而不是玩家(玩家数组)。
可能的解决方案:
players.forEach(player => player.pickUp(weapons));
players.forEach(player => player.dropOff(weapons));
推荐阅读
- wordpress - 联系表格 7:带有自定义文件上传按钮的邮件标签
- javascript - 如何降低字体大小以适应 div 中的新用户数字
- javascript - 淘汰赛 Js 多选绑定
- python - 在二维 Numpy 数组中查找最近的元素
- javascript - nuxt auth : Google 提供商返回 invalid_request
- vb.net - 在 Visual Basic 中创建带循环的直角三角形
- python - tensorflow:无法加载动态库“cudnn64_8.dll”;dlerror: 未找到 cudnn64_8.dll
- c - 返回局部变量的地址
- arrays - F# Array.FindIndex 异常处理
- c# - 将对象投射到任务
并从 Type 类型的变量中设置 T