【发布时间】:2012-06-26 04:07:22
【问题描述】:
我正在尝试为 HTML5 画布游戏创建一种存储和加载地图的方法。为此,我必须创建由变量引用的对象(函数)的新实例。这是我的代码。
function Map(w, h) {
if (typeof w == "undefined")
this.width = 640;
else
this.width = w;
if (typeof h == "undefined")
this.height = 480;
else
this.height = h;
this.obj = new Array();
this.x = new Array();
this.y = new Array();
this.backgroundColor = "#C0C0C0";
}
Map.prototype.addObject = function(cl, xx, yy) {
this.obj.push(cl);
this.x.push(xx);
this.y.push(yy);
}
function newInstance(o, x, y) {
this.tmp = new o(); //This is what doesn't work.
tmp.x = x;
tmp.y = y;
objects.push(tmp);
tmp.create();
}
Map.prototype.load = function() {
for (var i = 0; i < this.obj.length; i++) {
newInstance(this.obj[i], this.x[i], this.y[i]);
}
}
我希望它被这样使用:
//When I create the map.
var mMain = new Map();
//This cannot be new Player() and new Block() because I don't want to load the map yet. I'm just creating the map.
mMain.addObject(Player, 320, 240);
mMain.addObject(Block, 0, 256);
mMain.addObject(Block, 32, 256);
//etc...
//When I load the map.
mMain.load();
只是 Player 和 Block 对象如何工作的示例。
function Player() {
this.x = 0;
this.y = 0;
//Other variables irrelevant to this problem.
}
//Block object code
【问题讨论】:
-
为什么不能是:
mMain.addObject(new Player, 320, 240)? -
因为这将在创建地图时创建对象,而不是在加载时创建对象。所有地图都是在游戏开始时创建的,但只有在玩家进入该地图时才会加载。
-
将 Player 更改为
new Player()并将 Block 更改为new Block()另外,不要使用new Array()你应该只声明这样的数组[] -
是的,我发帖后才看到
-
您的
//doesn't work代码在这里可以正常工作 jsfiddle.net/xzxKp
标签: javascript function variables object instance