Reputation: 54
I'm working on a HTML5 Runner Game, the object runs continuously and on mouse event "click", he jumps. Then I add a hurdle to the Game and detect collision but it's not working properly. The problem is that when hurdle collide once with running object and detect collision, clear all objects and then redraw hurdle on canvas but as hurdle collide again and again with object hurdle's speed becoming fast and fast....:( Question is how to overcome it ? Here is the code:
function clearHurdle(){
h.clearRect(100,hy,160,250);
//if(hx==paiX||hy==paiY){
bl= new Image();
bl.onload= function(){
h.drawImage(bl,100,hy-20,160,250);
};
bl.src= "blast.png";
setTimeout(function(){
h.clearRect(100,hy-20,160,250);
show_char=0;
clearAll();
//drawpai();
hurdle();
},100);
}
function hurdle(){
if(hx>(paiX-2) && hx<(paiX+2) && hy>(paiY-2) && hy<(paiY+2)){
console.log(hx +'===='+(paiX-2));
clearHurdle();
hx=1360;
}
h.clearRect(hx,hy,170,250);
var img = new Image();
img.onload= function(){
h.drawImage(img,hx,hy,170,250);
}
img.src="hurdle.png";
hx-= 4.5;
if(hx>-400){
setTimeout(hurdle,1000/60);
}
show_char=1;
}
Upvotes: 0
Views: 296
Reputation: 25954
From what I can tell, the problem with the speed increasing as the game goes on is due to the duplicate setTimeouts created within your clearHurdle
function. The way you have it it works the first run through, but because the setTimeout calls the function hurdle
(which then calls clearHurdle
back in an endlessly continuing loop), it adds a second, third, fourth, etc. setTimeout to be ran.
If this is indeed your problem, you can fix it by declaring a variable name for the setTimeout within the clearHurdle
function, using the format var varName = setTimeout(function(){ ...Code Here... });
and use clearTimeout("varName")
to reset the setTimeout each time (unless you simply restructure the program to not require the functions calling each other)
Upvotes: 1