我正在使用p5.js,node.js和socket.io在浏览器中制作一个小型多人游戏。称为“播放器”的对象从一个客户端传递到另一个客户端以同步两个客户端。这适用于不依赖于方法调用的其他代码。但是现在我还想访问播放器对象中存储对象的方法,它不再起作用了。
这将是存储所有变量的对象,以及在两个客户端之间存储对象的数组:
var player = {
structures: []
};
现在,如果我像这样添加一个名为campfire的对象:
player.structures.push(new campfire(mouseX,mouseY));
并尝试调用对象campfire的draw()方法,如下所示:
class campfire {
constructor(x,y){
this.scale = 40;
this.x = x;
this.y = y;
this.maxLevel = 3;
this.button = new button(this.x, this.y+50, this.x-50, this.y-70, upgrade, upgrade_hover, this);
this.show_upgrade_button = true;
}
draw(){
switch(player.campfire.level){
case 1: image(fire, this.x, this.y, this.scale, this.scale);break;
case 2: image(campfire_2, this.x, this.y, this.scale, this.scale);break;
case 3: image(campfire_3, this.x, this.y, this.scale, this.scale);break;
default: console.log("cant upgrade, this shouldn't happen.");
}
if(this.show_upgrade_button){
this.button.draw();
}
}
trigger(){
if(player.campfire.level + 1 <= this.maxLevel && this.show_upgrade_button == true){
this.button.trigger();
}
}}
运用
player.structures[i].draw();
控制台(客户端没有使用对象'campfire'到数组'结构')打印出以下错误:
gui.js:38 Uncaught TypeError: player.structures[i].draw is not a function
将campfire对象推送到阵列的客户端能够进行draw()调用,并且不会打印错误消息。但是,未将对象推送到数组的其他客户端无法使用该方法并打印出错误,即使它们共享相同的“播放器”对象。奇怪的是,打印错误的那个仍然能够访问campfire对象的所有变量,因此它似乎只影响方法。
我发现的唯一资源是这篇文章https://airbrake.io/blog/javascript-error-handling/x-is-not-a-function-typeerror我试图将函数重命名为draw = function(){}和campfire.prototype.draw = function(){}但它对我没有任何影响。我认为这些功能没有被宣布正确吗?这对我来说是唯一可行的解释。
感谢您抽出时间阅读我的问题!
编辑:这是该项目的链接:https://github.com/Mayhoon/Multiplayer-Browsergame
我认为你的问题更多的是在设计层面上。 Socket.io(或任何其他同步库)并不意味着来回推送整段代码。在你的情况下,这将是篝火的功能。
我建议只来回推动state
。玩家有锤子吗?玩家有多少生命?玩家有篝火吗?换句话说,只同步不断变化的数据。
由于篝火(绘图功能)的功能对于所有玩家来说都是相同的,因此无需每隔几秒钟来回推送代码!效率很低!
相反,当您的同步对象显示玩家有篝火时,您可以在客户端中创建campfire实例。
在代码中看起来像这样(只是一个想法):
socket.io的同步对象
var player = {
structures: {campfire:true}
};
客户代码
// create campfire instances, tell the campfire which player it belongs to
if(player.structures.campfire) {
let cf = new Campfire(player)
cf.draw()
}
注意:很可能socket.io删除了可执行代码