我目前正在使用Javascript进行多人游戏,我的PlayerList数据结构/对象似乎有一个非常奇怪的问题。
这是对象:
var PlayerList = function(){
this.list = {};
}
该对象有几种方法,我通过这样做来添加......
PlayerList.prototype.method = function(){...}
方法是:addPlayer,removePlayer,playerInList,findPlayer,jsonify和unjsonify。 我对 unjsonify 有一个巨大的问题。这是代码:
PlayerList.prototype.unjsonify = function(jsonList){
var object = JSON.parse(jsonList);
var li = new PlayerList();
console.log(li.list.x);
console.log(li.list.y);
console.log(li.list);
//insert the fake player objects from the fake list into the new list as real player objects
for(p in object.list){
var pObj = object.list[p];
//create real player object
var player = new Player(pObj.name, pObj.x, pObj.y, pObj.velX, pObj.velY);
li.addPlayer(player);
}
return li;
}
这样做的原因是因为如果我只是解析服务器发送的jsonList对象,结果对象具有正确的结构,但PlayerList没有任何方法。
问题在于:我后来注意到,当我浏览PlayerList.list并绘制每个播放器时,我收到此错误:
未捕获的TypeError:对象NaN没有方法' getX'
事实证明,出于某种原因,当我在 unjsonify 中创建一个新的PlayerList时,它有两个额外的字段x和y,都设置为 NaN 。问题出现在这里:
PlayerList.prototype.unjsonify = function(jsonList){
var object = JSON.parse(jsonList);
var li = new PlayerList();
出于一些非常奇怪的原因,li 不一个新的空PlayerList就像它应该的那样。它包含两个额外的变量x和y,两者都设置为 NaN 。甚至更奇怪,不仅是它不是一个新的空列表,它包含当前服务器上的所有玩家 - 这对我来说似乎是不可能的,因为客户端第一次获得包含json播放器列表的包时它并没有。甚至还有自己过去的版本。
最重要的是,如果您查看 unjsonify ,console.log(li.list.x)和console.log(li.list.y)的代码块,则输出< em> undefined ,但是然后console.log(li.list)输出一个Object(除服务器上的所有播放器外)还有字段x和y设置为NaN。
我完全不知道如何发生这种情况。似乎没有人可以解决这些漏洞中的一个,因为它们没有任何意义。但如果有人对如何帮助我有任何想法,那将非常感激!
我应该注意,在我有这个PlayerList对象之前,我只是使用了一个没有任何方法的对象原语并手动完成所有操作(例如pList.username =播放器以添加玩家等等)并且一切正常(我可以看到其他玩家在我的屏幕上移动等等。)但是由于此时此刻变得非常大,我想添加一些结构,因此我创建了这个PlayerList对象,它应该使我的代码更加结构化和漂亮,但到目前为止只有造成的问题比其他任何问题都多。
答案 0 :(得分:0)
你的PlayerList没有.addPlay方法。
当您使用代码时,更容易将变量命名为可读代码。
function PlayerList() {
this.list = [];
};
//
PlayerList.prototype.unjsonify = function (jsonList) {
var jsonLst = JSON.parse(jsonList),
myPlayerList = new PlayerList(),
player,
jsonItem;
//
for (var i = 0; i < jsonLst.list.length; i++) {
jsonItem = jsonLst.list[i];
//
player = new Player(jsonItem.name, jsonItem.x, jsonItem.y, jsonItem.velX, jsonItem.velY);
myPlayerList.list.push(player);
};
return myPlayerList;
};
我已将您的Player.list从对象更改为数组。