2015-04-05 37 views
1

我有兩個點存儲在兩個變量中,它們形成一條線。我想從該線的一個終點找到一條垂直於該線的點。 (P1-P2)垂直於直線(P2,P3)並且相交於直線(P2,P3),並且相交(P1,P2)在P2。計算一條垂直於線條的點

+0

應該有一些更多的約束(至少一個更像P1P2的距離),因爲你已經提到躺在線上的任何一點工作條件垂直於P1P2並穿過P2。 – mushfek0001 2015-04-05 10:56:26

+0

垂直點與線之間的距離是否是任意選擇的? – MCHAppy 2015-04-05 11:23:29

回答

0

首先,角度:

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; 
0

我得到的答案在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); 
+0

這是一個JavaScript代碼,爲什麼'java'標籤? – MCHAppy 2015-04-05 11:31:26

+0

剛剛得到一個例子,所以我把它轉換成Java程序。但我分享了一些原始的例子 – 2015-04-06 03:21:19

0

您可以將您點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)); 
} 
0

如果你想使用Java,我可以推薦使用JTS。創建一個LineSegment並使用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);