I’m trying to create a way to store and load maps for an HTML5 canvas game. In order to do so, I must create new instances of objects (functions) referenced by a variable. This is my code.
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]);
}
}
I want it to be used as such:
//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();
Just an example of how the Player and Block objects work.
function Player() {
this.x = 0;
this.y = 0;
//Other variables irrelevant to this problem.
}
//Block object code
I figured out the problem. I had forgotten to check all of my code before posting, so I gave false information. Instead of “function Player()”, I had “var Player = ObjectResource;” because I wanted it to extend the ObjectResource function. I just had to change it to what I had posted.