我正在尝试为 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