【发布时间】:2021-08-25 06:00:14
【问题描述】:
如何计算相交两条线的反弹终点?
当给定以下两条线时,我能够使用以下函数计算两条线的交点。
export function intersection(line1, line2) {
line1.y1 *= -1; line1.y2 *= -1; // for Webpage coordinates
line2.y3 *= -1; line2.y4 *= -1; // for Webpage coordinates
const [x1, y1, x2, y2] = line1;
const [x3, y3, x4, y4] = line2;
const [a1, b1, c1] = [y2 - y1, x1 - x2, x2 * y1 - x1 * y2];
if ( a1 === 0 && b1 === 0 ) return 'line1 does not have length';
const [a2, b2, c2] = [y4 - y3, x3 - x4, x4 * y3 - x3 * y4];
if ( a2 === 0 && b2 === 0 ) return 'line2 does not have length';
const denom = a1 * b2 - a2 * b1;
if (denom === 0) return 'lines are parallel';
const x = (b1 * c2 - b2 * c1) / denom; // (x,y) is the intersection
const y = (a2 * c1 - a1 * c2) / denom;
// check if two lines are actually crossing w/o extending it
function getDist(x1, y1, x2, y2) {
return Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2);
}
const distLine1 = getDist(x1, y1, x2, y2);
const distLine2 = getDist(x3, y3, x4, y4);
const distToXY1 = Math.max(getDist(x1, y1, x, y), getDist(x2, y2, x, y)) ;
const distToXY2 = Math.max(getDist(x3, y3, x, y), getDist(x4, y4, x, y)) ;
if (distToXY1 > distLine1 || distToXY2 > distLine2)
return 'lines does not meet';
return {x, y};
}
演示:https://stackblitz.com/edit/intersection-of-two-lines?file=index.js
但是,我正在努力使用两条线找到两条线的反弹位置(或反射点)。
从line1(x1, x2, y1, y2)和line2(x1, x2, y1, y2)得到x/y位置的公式是什么?
【问题讨论】:
-
你必须得到与你击中的那条垂直的线,并且另一边与那条线的角度相同
-
就像在 3D 图形中反映法线
-
类似...函数 reflectLines(x,y,x2,y2,xx,yy,xx2,yy2){var slope1=(y-y2)/(x-x2);var slope2 =(yy-yy2)/(xx-xx2);var angleFromOrigin=Math.asin(slope1); var angleFromOrigin2=Math.asin(slope2);var reciprical=1.0/(slope1);var reciprical2=1.0/(slope2);var angleToReciprical=Math.acos(reciprical/slope1);var angleToReciprical2=Math.acos(reciprical2/slope2 );var newSlope=sin(angleFromOrigin2+Math.rad(90)+angleToReciprical); var newSlope2=sin(angleFromOrigin+Math.rad(90)+angleToReciprical2);return [newSlope,newSlope2];} 我可能混淆了我的一些数学但类似的东西。
标签: javascript math