【发布时间】:2014-11-10 17:39:50
【问题描述】:
我的程序中目前有以下行。我还有另外两个整数变量,x 和 y。
我想看看这个新点(x, y) 是否在这条线上。我一直在看以下线程:
Given a start and end point, and a distance, calculate a point along a line
我想出了以下几点:
if(x >= x1 && x <= x2 && (y >= y1 && y <= y2 || y <= y1 && y >= y2))
{
float vx = x2 - x1;
float vy = y2 - y1;
float mag = sqrt(vx*vx + vy*vy);
// need to get the unit vector (direction)
float dvx = vx/mag; // this would be the unit vector (direction) x for the line
float dvy = vy/mag; // this would be the unit vector (direction) y for the line
float vcx = x - x1;
float vcy = y - y1;
float magc = sqrt(vcx*vcx + vcy*vcy);
// need to get the unit vector (direction)
float dvcx = vcx/magc; // this would be the unit vector (direction) x for the point
float dvcy = vcy/magc; // this would be the unit vector (direction) y for the point
// I was thinking of comparing the direction of the two vectors, if they are the same then the point must lie on the line?
if(dvcx == dvx && dvcy == dvy)
{
// the point is on the line!
}
}
它似乎不起作用,还是这个想法很糟糕?
【问题讨论】:
-
它是二维的,为什么不简单地将 (x,y) 放在从 (x1,y1) 和 (x2,y2) 获得的直线方程中?
-
(x, y)是一个点(如标题所示)还是一个向量(如问题所示)?这个问题似乎只有当它是一个点时才真正有意义,但也许你在谈论由两个向量定义的线是否相交? -
首先,请说明您的条件/假设。如果您正在处理浮点数,则必须考虑浮点数的不准确性。将数学直接转化为公式是行不通的。
-
@JerryCoffin 一点!为不一致的符号道歉。
-
见this