Collision detection in html5 canvas

杀马特。学长 韩版系。学妹 提交于 2019-11-29 05:18:51

[ 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/

    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/

// 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
    )
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!