Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Is a line stretching from (a,b) to (c,d) touching Point(x,y)?

Tags:

java

graphics

I'm writing a tool in Java which does a little drawing on a Graphics object.

But, I'm stuck on a problem that I don't quite know how to solve. Hoping someone can help.

How can I determine if a point x,y on a Graphics object touches a line that extends from, for example, 200,200 to 392,144.

Sounds simple, but I'm stumped...help!

like image 386
rog8gm Avatar asked Jun 08 '11 08:06

rog8gm


4 Answers

That has little to do with the Graphics object, actually. It's just some simple math.

Your example line has the formula

        

with t in [0, 1]. So to find out whether the point is on the line, just solve the linear equation system

        

If t is the same for both equations in the system and between 0 and 1, you have a solution. So you need to calculate:

        

Unless my math fails me; it's been a while.

like image 80
Joey Avatar answered Oct 17 '22 09:10

Joey


There are correct answers already, but I think it might be more generally useful to have a formula that gives the distance of any point from a specified line. Then you can just check if this is zero, or within whatever tolerance you choose. The following should work regardless of special cases like vertical lines (infinite gradient).

The distance of point X from the line AB is

    

where A, B and X are the 3D position vectors of the three points (just set z = 0 if you are only working in 2D) and x is the vector product. That comes to

    

where A = (a,b), B = (c,d) and X = (x,y). Then to check that the point is actually within the line segment and not elsewhere on the infinite line, you can use the scalar products: the distance of X along the line from A to B is

    

i.e.

    

and this should lie between 0 and

like image 33
Ben Avatar answered Oct 17 '22 09:10

Ben


You can work out the equation of the line connecting the two points.

Equation of line: y = mx+c

m is the gradient: m = (y2-y1)/(x2-x1);

c is the y-intercept: c = y1 - m * x1;

Once you have your equation, you can test whether any point lies on the line by plugging in its x-coordinate and checking if the y-coordinate coming out from the equation matches.

like image 30
dogbane Avatar answered Oct 17 '22 08:10

dogbane


This has been already answered here: How can I tell if a point belongs to a certain line?.

like image 1
Ryan Fernandes Avatar answered Oct 17 '22 08:10

Ryan Fernandes