简体   繁体   English

HTML5 Canvas游戏冲突检测问题

[英]HTML5 Canvas Game Collision Detection issue

I'm working on a HTML5 Runner Game, the object runs continuously and on mouse event "click", he jumps. 我正在开发HTML5 Runner Game,该对象连续运行,并且在鼠标事件“ click”下他跳了起来。 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;
}

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. 据我所知,随着游戏的进行,速度增加的问题是由于在clearHurdle函数中创建的setTimeouts重复。 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. 使用它的方式,它会在第一次运行时起作用,但是由于setTimeout调用了函数hurdle (它随后在无休止的连续循环中调用clearHurdle ),因此它将添加第二,第三,第四等setTimeout来运行。

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... }); 如果这确实是您的问题,可以通过使用clearHurdle函数中的setTimeout声明一个变量名称来解决它,格式为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) 并使用clearTimeout("varName")每次都重置setTimeout(除非您只是简单地重组程序以不需要相互调用的函数)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM