如何获取沿一条线发生碰撞的百分比?



我正在使用此碰撞检测功能来确定 A) 线段是否与圆相交,以及 B) 发生碰撞的线段向下多远。

我不太擅长数学,所以这不是我自己编写的函数,检测碰撞似乎可以正常工作,但是当它到达截距点时,我得到了我没想到的值。我试图以百分比形式获取发生碰撞的线的距离,因此例如,如果线段100px长,并且圆50px沿线碰撞,我希望函数返回50px,从中我可以轻松计算百分比。

function interceptOnCircle(p1, p2, c, r) {
console.log(arguments);
//p1 is the first line point
//p2 is the second line point
//c is the circle's center
//r is the circle's radius
var p3 = {
x: p1.x - c.x,
y: p1.y - c.y
}; //shifted line points
var p4 = {
x: p2.x - c.x,
y: p2.y - c.y
};
var m = (p4.y - p3.y) / (p4.x - p3.x); //slope of the line
var b = p3.y - m * p3.x; //y-intercept of line
var underRadical = Math.pow(r, 2) * Math.pow(m, 2) + Math.pow(r, 2) - Math.pow(b, 2); //the value under the square root sign
if (underRadical < 0) {
//line completely missed
return false;
} else {
var t1 = (-m * b + Math.sqrt(underRadical)) / (Math.pow(m, 2) + 1); //one of the intercept x's
var t2 = (-m * b - Math.sqrt(underRadical)) / (Math.pow(m, 2) + 1); //other intercept's x
var i1 = {
x: t1 + c.x,
y: m * t1 + b + c.y
}; //intercept point 1
var i2 = {
x: t2 + c.x,
y: m * t2 + b + c.y
}; //intercept point 2
console.log('Collision points: [' + i1.x + ', ' + i1.y + '], [' + i2.x + ', ' + i2.y + ']')
var distance = Math.hypot(p1.x - i2.x, p1.y - i2.y);
return distance;
}
}

对于50px长的行之间的碰撞,我得到以下日志:

Collision points: [111.91311159515845, 90.88529912057992], [92.30169719247377, 112.87385466298396]

var distance = Math.hypot(p1.x - i2.x, p1.y - i2.y);会导致值比行本身长。我希望distance值在 0 到 50 之间。如何获取沿一条线(从p1)发生碰撞的百分比?

编辑:只是为了验证我正在测试的行是否正确长度,我用console.log(Math.hypot(p1.x - p2.x, p1.y - p2.y)); //returns 49对其进行了测试

我认为问题可能是您没有将解决方案限制在两个原始点之间的解决方案。

您正在计算与y = mx + c给出的线的相交,其中m是从两个点计算的梯度,c是第一点,但这是一条无限长的线,因此您可以在两个原始点之外获得交点。

最简单的方法是根据需要计算百分比,并得出结论,小于 0 或大于 100% 的任何值实际上都不是与两点之间的线段的有效交集。

var length = Math.hypot(p1.x - p2.x, p1.y - p2.y);
var distance1 = Math.hypot(p1.x - i2.x, p1.y - i2.y);
var distance2 = Math.hypot(p1.x - i1.x, p1.y - i1.y);
var lowerBounds = Math.min(distance1, distance2);
if (lowerBounds < length) {
return lowerBounds;
} else {
return false;
}

最新更新