计算一个垂直于直线的点

Calculate a point which is perpendicular to a line

本文关键字:垂直 于直线 一个 计算      更新时间:2023-09-26

我在两个变量中存储了两个点,这形成了一条线。我想从直线的一个端点找到一个垂直于直线的点。

假设我有两个点P1(x1,y1)和P2(x2,y2),那么我想找到第三个点P3,使得线(P1-P2)垂直于线(P2,P3)并在P2相交。

首先,角度:

public static double angle (double x1, double y1, double x2, double y2) {
    double xdiff = x1 - x2;
    double ydiff = y1 - y2;
    //double tan = xdiff / ydiff;
    double atan = Math.atan2(ydiff, xdiff);
    return atan;
}

要获得垂线,必须将PI/2添加到由两点定义的直线的角度上。

一旦你有了这个角度,公式就是:

x = interceptPt.x + sin(perp_angle) * distance;
y = interceptPt.y + cos(perp_angle) * distance;

如果你想使用Java,我可以建议你使用JTS。创建线段并使用pointAlongOffset方法。给定点p1和p2,代码看起来是这样的:

// create LineSegment
LineSegment ls = new LineSegment(p1.getX(), p1.getY(), p2.getX(), p2.getY());
// perpendicular distance to line
double offsetDistance = 10;
// calculate Point right to start point
Coordinate startRight = ls.pointAlongOffset(0, offsetDistance);
// calculate Point left to start point
Coordinate startLeft = ls.pointAlongOffset(0, -offsetDistance);
// calculate Point right to end point
Coordinate endRight = ls.pointAlongOffset(1, offsetDistance);
// calculate Point left to end point
Coordinate endLeft = ls.pointAlongOffset(1, -offsetDistance);

ControlAltDel已经得到回答,但他犯了一个错误,将cos替换为sin

x = interceptPt.x + cos(angle + 90) * distance;
y = interceptPt.y + sin(angle + 90) * distance;

x、 y是在(距离)处远离(interceptPt.x,interceptPt.y)的点。

(interceptPt.x,interceptPt.y)是直线上绘制垂直起点的点。

angle=您与水平轴的线角度

我在http://jsfiddle.net/eLxcB/2/

// Start and end point
var startX = 120
var startY = 150
var endX = 180
var endY = 130
R.circle(startX,startY,2);
// Calculate how far above or below the control point should be
var centrePointX = startX
var centrePointY = startY;
// Calculate slopes and Y intersects
var lineSlope = (endY - startY) / (endX - startX);
var perpendicularSlope = -1 / lineSlope;
var yIntersect = centrePointY - (centrePointX * perpendicularSlope);
// Draw a line between the two original points
R.path('M '+startX+' '+startY+', L '+endX+' '+endY);
// Plot some test points to show the perpendicular line has been found
R.circle(100, (perpendicularSlope * 100) + yIntersect, 2);

您可以将点存储在vec2d中,然后使用一些数学方程来获得垂直点。

vec2d getPerpendicularPoint(vec2d A, vec2d B, float distance)
{
   vec2d M = (A + B) / 2;
   vec2d p = A - B;
   vec2d n = (-p.y, p.x);
   int norm_length = sqrt((n.x * n.x) + (n.y * n.y));
   n.x /= norm_length;
   n.y /= norm_length;
   return (M + (distance * n));
}