I'm just wondering how to instantiate the same objects that all share the same variables, except their positions.
I'm basically working on the scene of my HTML5 game, and I've build a streetlamp post that turns on and off. All the lamps will have the same variables, such as Image, Size, on/off function. The only thing that will be different will be the position x and y.
I've built my lamp within a variable function (I think they're called that var = {
), and within my actual game DrawFunction
, I'm calling LampPost.draw();
.
Is it possible to do something like this?
LampPost(0,0);
LampPost(100, 0);
LampPost(200, 0);
etc ... and then possibly place each instantiate Lamp
within an array?
This is a snippet code for the lamp:
var LampPost = {
lamp_xsprite : 0,
lamp_ysprite : 0,
light_xsprite : 0,
lightysprite : 0,
x : 440,
y : 320,
//Flicker effects
lightFlicker : 0,
seconds_Off : 0,
seconds_On : 0,
randomLength_Off : 500,
randomLength_On : 150,
draw: function(x, y) {
this.x = x;
this.y = y;
ctxPropsOver.setTransform(1, 0, 0, 1, -Map.x + gameWidth/2, -Map.y + gameHeight/2);
ctxPropsOver.rotate(Math.PI / -25);
ctxPropsOver.clearRect(0, 0, 1000, 1000);
ctxPropsOver.globalAlpha = this.lightFlicker;
ctxPropsOver.drawImage(imgLights, 0, 36, 500, 463, -60 + this.x, -190 + this.y, 500, 463);
ctxPropsOver.globalAlpha = 1;
ctxPropsOver.drawImage(imgLights, 0, 0, 210, 36, 0 + this.x, 0 + this.y, 210, 36);
----- UPDATE -----
Okay, So I've converted it into an instance of object, this is what I have so far:
LampPost = function(lx, ly, la){
x = lx; //500;
y = ly; //335;
centrex = 12;
centrey = 17;
rotate = la; //-8;
}
LampPost.prototype.draw = function (){
ctxPropsOver.setTransform(1, 0, 0, 1, (-Map.x + gameWidth/2), (-Map.y + gameHeight/2) );
ctxPropsOver.clearRect(0, 0, 1000, 1000);
ctxPropsOver.save();
ctxPropsOver.translate(this.x, this.y);
ctxPropsOver.rotate(this.rotate*Math.PI/180);
ctxPropsOver.translate(-this.centrex, -this.centrey);
ctxPropsOver.globalAlpha = this.lightFlicker;
ctxPropsOver.drawImage(imgLights, 0, 36, 500, 463, -60, -190, 500, 463);
ctxPropsOver.globalAlpha = 1;
ctxPropsOver.drawImage(imgLights, 0, 0, 210, 36, 0, 0, 210, 36);
ctxPropsOver.restore();
};