我正在寻找一个确定的答案,可能是一个函数我很慢,这将决定一个线段和圆圈是否已经碰撞,在javascript(使用画布)
像下面那样的函数如果碰撞则返回true,否则返回false将是很棒的。我甚至可能会给你一个孩子。
function isCollided(lineP1x, lineP1y, lineP2x, lineP2y, circlex, circley, radius) {
...
}
我发现了很多公式,like this one,但它们在我的头上。
在这里你需要一些数学:
如果您不知道如何解决方程式,这是基本概念。我会把剩下的想法留给你。 ;)弄清楚CD
的长度并不难。
如果您正在询问如何,那就是:在JavaScript中查找冲突有点复杂。
我花了大约一天半的时间来完善它。希望这会有所帮助。
function collisionCircleLine(circle,line){ // Both are objects
var side1 = Math.sqrt(Math.pow(circle.x - line.p1.x,2) + Math.pow(circle.y - line.p1.y,2)); // Thats the pythagoras theoram If I can spell it right
var side2 = Math.sqrt(Math.pow(circle.x - line.p2.x,2) + Math.pow(circle.y - line.p2.y,2));
var base = Math.sqrt(Math.pow(line.p2.x - line.p1.x,2) + Math.pow(line.p2.y - line.p1.y,2));
if(circle.radius > side1 || circle.radius > side2)
return true;
var angle1 = Math.atan2( line.p2.x - line.p1.x, line.p2.y - line.p1.y ) - Math.atan2( circle.x - line.p1.x, circle.y - line.p1.y ); // Some complicated Math
var angle2 = Math.atan2( line.p1.x - line.p2.x, line.p1.y - line.p2.y ) - Math.atan2( circle.x - line.p2.x, circle.y - line.p2.y ); // Some complicated Math again
if(angle1 > Math.PI / 2 || angle2 > Math.PI / 2) // Making sure if any angle is an obtuse one and Math.PI / 2 = 90 deg
return false;
// Now if none are true then
var semiperimeter = (side1 + side2 + base) / 2;
var areaOfTriangle = Math.sqrt( semiperimeter * (semiperimeter - side1) * (semiperimeter - side2) * (semiperimeter - base) ); // Heron's formula for the area
var height = 2*areaOfTriangle/base;
if( height < circle.radius )
return true;
else
return false;
}
这就是你如何做到的..
Matt DesLauriers在https://www.npmjs.com/package/line-circle-collision上发布了一个针对此问题的Javascript库。 API非常简单:
var circle = [5, 5],
radius = 25,
a = [5, 6],
b = [10, 10]
var hit = collide(a, b, circle, radius)