Help calculating a perpendicular line end point.
-
I am working in C++. I am trying to draw a perpendicular hash mark from the start of a sloped line. My code below draws a perpendicular line but when the slope of the original line changes the hash mark appears to change length. When the line is close to horizontal the hash mark looks longest and shortest when the line is close to vertical. I believe the problem is the fixed value for HashLength. Can you show a better way to calculate the end of the perpendicular line(px2,py2) so my hash mark always looks the same size.
//(x1,y1)(x2,y2) //original Line
//(x1,y1)(px1,px2) //Perpendicular LineOrig_Line_Slope = (y1-y2)/(x1-x2);
Recipical_Slope = ((1.0 / Orig_Line_Slope)*-1);HashLength = 10.0;
px2 = (x1+HashLength);
py2 = (y1+(Orig_Line_Slope*HashLength));MoveToEx(hdc, x1, y1, NULL);
LineTo(hdc, px2, py2 ); -
I am working in C++. I am trying to draw a perpendicular hash mark from the start of a sloped line. My code below draws a perpendicular line but when the slope of the original line changes the hash mark appears to change length. When the line is close to horizontal the hash mark looks longest and shortest when the line is close to vertical. I believe the problem is the fixed value for HashLength. Can you show a better way to calculate the end of the perpendicular line(px2,py2) so my hash mark always looks the same size.
//(x1,y1)(x2,y2) //original Line
//(x1,y1)(px1,px2) //Perpendicular LineOrig_Line_Slope = (y1-y2)/(x1-x2);
Recipical_Slope = ((1.0 / Orig_Line_Slope)*-1);HashLength = 10.0;
px2 = (x1+HashLength);
py2 = (y1+(Orig_Line_Slope*HashLength));MoveToEx(hdc, x1, y1, NULL);
LineTo(hdc, px2, py2 );//Denote change in x =dx //Denote change in y =dy float dx=0.0; float dy=0.0; //Then dx^2 + dy^2 = HashLength ^2 ..eq 1 //We can express dy in terms of dy because // dy/dx= Recipical_Slope // simplifying.. // dy=Recipical_Slope*dx //Replacing dy in eq 1, we have //dx^2 + (Recipical_Slope *dx)^2= HashLength^2 //simplifying.. dx=sqrt(HashLength^2/(1+Recipical_Slope^2)); dy=Recipical_Slope * dx; px2=x1+dx; py2=y1+dy;
-
//Denote change in x =dx //Denote change in y =dy float dx=0.0; float dy=0.0; //Then dx^2 + dy^2 = HashLength ^2 ..eq 1 //We can express dy in terms of dy because // dy/dx= Recipical_Slope // simplifying.. // dy=Recipical_Slope*dx //Replacing dy in eq 1, we have //dx^2 + (Recipical_Slope *dx)^2= HashLength^2 //simplifying.. dx=sqrt(HashLength^2/(1+Recipical_Slope^2)); dy=Recipical_Slope * dx; px2=x1+dx; py2=y1+dy;
To Yang Kok Wah I tested your solution and it works very well. Thank You