我正在研究一個HTML5 Runner Game,該對象連續運行,並在鼠標事件「單擊」時跳躍。然後我給遊戲添加一個障礙並檢測碰撞,但是它不能正常工作。問題是,當障礙與跑步物體碰撞一次並檢測到碰撞時,清除所有物體,然後在畫布上重新繪製障礙物,但障礙物一次又一次與對象障礙物的速度變得快速和快速碰撞.... :( 問題是如何克服它下面是代碼:?HTML5 Canvas遊戲碰撞檢測問題
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;
}
我相信這是因爲'clearHurdle'函數中的setInterval。它第一次運行良好,但是因爲setTimeout調用函數'hurdle'(然後調用'clearHurdle'回到一個無止境的循環中),因此增加了第二個setInterval。爲了解決這個問題,你需要爲setInterval聲明一個變量名,並使用'clearInterval(varName)'來每次重置它 –
謝謝@Zeaklous它的工作。 :)感謝您的幫助巴迪。 –