Re: Find point perpendicular to line
Joshua Cranmer wrote:
On Sun, 22 Jul 2007 14:13:22 -0400, Jeff Higgins wrote:
Lew wrote:
Jeff Higgins wrote:
I would like to find a third point that is:
on a line perpendicular to lineAB,
and passes throught point A
and
double distanceC = 3d;
distant from A
I belive this is your criteria:
C
| -- distance 3d.
B-----A
If the line AB is at an angle theta to the origin line, then theta =
arctan (Ay-By)/(Ax-Bx). The angle that line AC makes with the origin is
phi, which is theta + pi/2 in this case. Translating the origin to point
A, we have that Cx is r*cos phi and Cy is r*sin phi.
phi should also be equal to arctan (Bx-Ax)/(Ay-By), and reducing, we get
the Cx = 3d / sqrt (1+x^2) + Ax and Cy = 3d * x /sqrt(1+x^2) + Ay where x
is (Bx-Ax)/(Ay-By), except if Ay=By (i.e., a horizontal line), where Cx =
Ax and Cy = Ay+3d.
Note: only checked for slope AB = 0, 1, and infinity.
Joshua,
Thanks very much.
Appreciative,
JH
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class HitTestBoundsTest
{
static class GraphicPanel extends JPanel
{
Point2D.Double getMyPoint_PerpendicularToALine(
Point2D.Double source,
Point2D.Double target,
double width)
{
// TODO test for horizontal line
double x = ((target.x - source.x) / (source.y - target.y));
double cx = (width / 2) / Math.sqrt(1 + Math.pow(x, 2)) + source.x;
double cy = (width / 2) * x / Math.sqrt(1 + Math.pow(x, 2)) +
source.y;
Point2D.Double ret = new Point2D.Double(cx, cy);
return ret;
}
public void paintComponent( Graphics g )
{
Graphics2D g2 = (Graphics2D)g;
Path2D.Double line = new Path2D.Double();
line.moveTo(source.x, source.y);
line.lineTo(target.x, target.y);
Point2D.Double C =
getMyPoint_PerpendicularToALine(source, target, width);
Point2D.Double D =
getMyPoint_PerpendicularToALine(target, source, width);
Path2D.Double CD = new Path2D.Double();
Path2D.Double EF = new Path2D.Double();
Path2D.Double CE = new Path2D.Double();
Path2D.Double DF = new Path2D.Double();
CD.moveTo(C.x, C.y);
CD.lineTo(D.x, D.y);
EF.moveTo(C.y, C.x);
EF.lineTo(D.y, D.x);
CE.moveTo(C.x, C.y);
CE.lineTo(C.y, C.x);
DF.moveTo(D.x, D.y);
DF.lineTo(D.y, D.x);
g2.draw(CD);
g2.draw(EF);
g2.draw(CE);
g2.draw(DF);
g2.setColor(Color.RED);
g2.draw(line);
}
public GraphicPanel(){}
Point2D.Double source =
new Point2D.Double(100d, 100d);
Point2D.Double target =
new Point2D.Double(200d, 200d);
double width = 3d;
}
JFrame frame;
JPanel panel;
HitTestBoundsTest()
{
frame = new JFrame("HitTestBoundsTest");
panel = new GraphicPanel();
frame.setSize(600, 480);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setVisible(true);
}
public static void main(String[] args)
{
HitTestBoundsTest test = new HitTestBoundsTest();
}
}