【发布时间】:2012-12-18 16:54:15
【问题描述】:
我有动态生成动画的线条,我想检测线条何时撞到另一条线条。我正在尝试实现一些基本的线性代数来获得线的方程,然后求解 x,y,但结果不稳定。在这一点上,我只用两条线进行测试,这意味着我应该得到一个交点,但我得到了两个。我只是想确保我的数学没问题,我应该在别处寻找问题。
function collision(boid1, boid2) {
var x1 = boid1.initialX, y1 = boid1.initialY, x2 = boid1.x, y2 = boid1.y, x3 = boid2.initialX, y3 = boid2.initialY, x4 = boid2.x, y4 = boid2.y;
slope1 = (y1 - y2)/(x1 - x2);
slope2 = (y3 - y4)/(x3- x4);
if(slope1 != slope2){
var b1 = getB(slope1,x1,y1);
var b2 = getB(slope2,x3,y3);
if(slope2 >= 0){
u = slope1 - slope2;
}else{
u = slope1 + slope2;
}
if(b1 >= 0){
z = b2 - b1;
}else{
z = b2 + b1;
}
pointX = z / u;
pointY = (slope1*pointX)+b1;
pointYOther = (slope2*pointX)+b2;
console.log("pointx:"+pointX+" pointy:"+pointY+" othery:"+pointYOther);
context.beginPath();
context.arc(pointX, pointY, 2, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 1;
context.strokeStyle = '#003300';
context.stroke();
}
return false;
}
function getB(slope,x,y){
var y = y, x = x, m = slope;
a = m*x;
if(a>=0){
b = y - a;
}else{
b = y + a;
}
return b;
}
问题是我得到了两个不同的交点值。应该只有一个,这让我相信我的计算是错误的。是的,x2,y2,x4,y4 都在移动,但它们有一个固定的角度,一致的坡度证实了这一点。
【问题讨论】:
-
请添加一个short self-contained example,它显示了问题。目前,您的帖子既缺少问题又缺少问题,它应该至少包含其中一个。 (注意:您告诉我们结果不稳定,但您没有告诉我们问题的确切性质)。
-
你不断检查事情是否积极的事实是一个危险信号。这不应该是必要的。此外,您绝对没有处理其中一条线是垂直的情况(即
slope = Infinity)。 -
Aaron,我的做法是像人类试图解决变量一样。什么是更有效的方法?
标签: javascript linear-algebra intersection