(Renkum, Tuesday 5th of June 2012)

And now we'll add some dynamic

I spent another half an hour in reading an MSDN blog about game acceleration, I didn't use the whole part about off-screen canvasses and requesting animation frames (I probably will when I'm more experienced.), but I read all of the code and took what I needed to add some dynamic to my code.

I will try to add some dynamic with an interval, I will use the window-object to set a timer interval on a method that performs my next step (and I refactored some variable names):

.
.
var hunterPosX = curStartPos;
var hunterPosY = 0;
initField(fields, hunterPosX); 
drawField(fields, hunterPosX);

window.setInterval(nextStep, 1000);

function initField(fieldArray, hunterPositionX){
.
.

I refactored some code and added two methods for drawing my item:

function drawItem(x,y){
	ctx.fillRect(x*itemWidth
	           ,(fieldHeight-y-1)*itemHeight
			   ,itemWidth,itemHeight)
}
function setFillStyle(itemType){
    if (itemType == 1) ctx.fillStyle='#FF0000';
	else if (itemType == 2) ctx.fillStyle='#00FF00';
	else ctx.fillStyle='#DDDDFF';
}

And the new nextStep method looks like:

function nextStep(){
	var newHunterPosY = hunterPosY+1;
	if (newHunterPosY >= fieldHeight) newHunterPosY = 0;
	//redraw the hunter
	ctx.fillStyle='#0000FF';
	drawItem(hunterPosX, newHunterPosY);
	var oldItem = fields[hunterPosX + hunterPosY * fieldWidth];
	setFillStyle(oldItem);	 
	drawItem(hunterPosX, hunterPosY);
	hunterPosY = newHunterPosY;
}

When you open the resulting HTML5 page, the blue hunter will start at the bottom of the field and go up.

To check that result, click here.

 


Day1 Day2 Day3 Day4
Day5 Day6 Day7
back to index