javascript html5 画布中的碰撞检测

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20885297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:32:47  来源:igfitidea点击:

Collision detection in html5 canvas

javascriptjqueryhtmlcanvascollision-detection

提问by Sora

I'm trying to build a game where the user should place the circle inside a vertical bar but I'm having trouble in the collision detection function. Here is my jsfiddle : http://jsfiddle.net/seekpunk/QnBhK/1/

我正在尝试构建一个游戏,用户应该将圆圈放在垂直条内,但我在碰撞检测功能中遇到了问题。这是我的 jsfiddle:http: //jsfiddle.net/seekpunk/QnBhK/1/

 if (collides(Bluecircle, longStand)) {
    Bluecircle.y = longStand.y2;
    Bluecircle.x = longStand.x2;
 }
 else if (collides(Bluecircle, ShortStand)) {
    Bluecircle.y = ShortStand.y2;
    Bluecircle.x = ShortStand.x2;
 }
function collides(a, bar) {
   return a.x == bar.x1 && a.y == bar.y1;
}

回答by markE

[ Edited to fix a typo and an omission ]

[已编辑以修复拼写错误和遗漏]

Here's how to hit-test a rectangle and a circle for collision:

以下是对矩形和圆形进行碰撞测试的方法:

Demo: http://jsfiddle.net/m1erickson/n6U8D/

演示:http: //jsfiddle.net/m1erickson/n6U8D/

    var circle={x:100,y:290,r:10};
    var rect={x:100,y:100,w:40,h:100};

    // return true if the rectangle and circle are colliding
    function RectCircleColliding(circle,rect){
        var distX = Math.abs(circle.x - rect.x-rect.w/2);
        var distY = Math.abs(circle.y - rect.y-rect.h/2);

        if (distX > (rect.w/2 + circle.r)) { return false; }
        if (distY > (rect.h/2 + circle.r)) { return false; }

        if (distX <= (rect.w/2)) { return true; } 
        if (distY <= (rect.h/2)) { return true; }

        var dx=distX-rect.w/2;
        var dy=distY-rect.h/2;
        return (dx*dx+dy*dy<=(circle.r*circle.r));
    }

[Added answer given clarification]

[添加了澄清的答案]

...And this is how to test if the circle is completely contained in the rectangle

...这是如何测试圆是否完全包含在矩形中

Demo: http://jsfiddle.net/m1erickson/VhGcT/

演示:http: //jsfiddle.net/m1erickson/VhGcT/

// return true if the circle is inside the rectangle
function CircleInsideRect(circle,rect){
    return(
        circle.x-circle.r>rect.x &&
        circle.x+circle.r<rect.x+rect.w &&
        circle.y-circle.r>rect.y &&
        circle.y+circle.r<rect.y+rect.h
    )
}