答案是 X=270 Y=395
首先将斜率 V 定义为 dy/dx =(y2-y1)/(x2-x1)。在您的示例中: (35-20)/(30-20)=1.5
直线方程为 y = V * (x-x1) + y1。您对水平位置 x 感兴趣:y= CH/2 OR y= H-CH/2 所以(不是代码,只是数学)
if (y2-y1)<0:
x=(CH/2 -y1)/V +x1 10 for your example. OR
if (y2-y1)>0:
x=(H-CH/2 -y1)/V +x1 270 for your example
else (that is: y2==y1)
the upper or lower lines were not hit.
if CH/2 <= x <= W-CH/2 the circle did hit the that upper or lower side: since V>0, we use x=270 and that is within CH/2 and W-CH/2.
所以你的问题的答案是 y=H-CH/2 = 395 , X=270
对于侧线,它是相似的:
(if (x2-x1)<0)
y=(CH/2 -x1)*V +y1
(if (x2-x1)>0)
y=(W-CH/2 -x1)*V +y1
else (that is: x2==x1)
the side lines were not hit.
if CH/2 <= y <= H-CH/2 the circle did hit that side at that y.
小心完全水平或垂直移动的琐碎情况,以免除以零。计算 V 或 1/V 时。还要处理圆圈根本不动的情况。
既然您现在问了,这里是元代码,您应该可以轻松地将其转换为真正的方法。它也处理特殊情况。输入是您在示例中列出的所有变量。我在这里只使用一个符号来表示圆的大小,因为它是圆而不是椭圆。
method returning a pair of doubles getzy(x1,y1,W,H,CH){
if (y2!=y1){ // test for hitting upper or lower edges
Vinverse=(x2-x1)/(y2-y1)
if ((y2-y1)<0){
xout=(CH/2 -y1)*Vinverse +x1
if (CH/2 <= y <= H-CH/2) {
yout=CH/2
return xout,yout
}
}
if ((y2-y1)>0){
xout=(H-CH/2 -y1)*Vinverse +x1
if (CH/2 <= y <= H-CH/2) {
yout=H-CH/2
return xout,yout
}
}
}
// reaching here means upper or lower lines were not hit.
if (x2!=x1){ // test for hitting upper or lower edges
V=(y2-y1)/(x2-x1)
if ((x2-x1)<0){
yout=(CH/2 -x1)*V +y1
if (CH/2 <= x <= W-CH/2) {
xout=CH/2
return xout,yout
}
}
if ((x2-x1)>0){
yout=(H-CH/2 -x1)*V +y1
if (CH/2 <= x <= W-CH/2) {
xout=H-CH/2
return xout,yout
}
}
}
// if you reach here that means the circle does not move...
deal with using exceptions or some other way.
}