Creating games in Browser (scratchbook)

Game loop

The traditional way of generating a loop inside javascript would be to use window.setInterval with a callback function.  It seems best to use window.requestAnimationFrame(). This method seems to be running in a separate GUI thread for the browser.

Because this is called whenever the browser sees fit you need to keep track of time yourself to ensure you need to update at all

CSS sprites (source)

It is possible to create css sprites like so:

generateButton(id,img,x,y,parent){
var btnRes = new Image();
btnRes.id = id;
btnRes.style.width = "16px";
btnRes.style.height= "16px";
btnRes.style.background = "url('"+img+"') no-repeat "+x+" "+y;
btnRes.addEventListener("click",(e)=>{this.onBtnClick(e)});
parent.appendChild(btnRes);
}

where x and y are css coordinates. For instance (imgZones points to a png file):

this.generateButton(“residential”,imgZones,”0″,”-16px”,this.node);

This is to create sprites on the Dom.

Canvas sprites (source):

Canvas sprites can be used like so :

context.drawImage(this.getSprite(),this.offsetX,this.offsetY,this.width,this.height,x,y,this.width,this.height);

getSprite() returns an image object ( var x = new image(); x.src = “somegraphic.png”);

the offset is the place where you want to start clipping. The image used contains several icons that start at a certain point.

Prevents lots of loops

When creating a game sooner or later you will end up writing multiple layers of graphics ( multiple canvases ). If you have a grid of lets say 640*480 pixels dividided by tiles of 16*16 you have a multi dim array of 40*30. In other words. 1200 * layercount places to check if something needs to be done.

Keep this in mind always. So that when you have a layer that only shows a single type of graphic for all 1200 tiles dont redraw that layer all the time but just once or when it is needed. Computer power is not very limited nowadays but just for the sake of it think about this.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.