Java Reference
In-Depth Information
Creating a Point from Two Lines
You can add the method to determine the point of intersection between two lines to the Line class. Figure
5-8 illustrates how the mathematics works out.
FIGURE 5-8
You can ignore the mathematics if you want to, as it is not the most important aspect of the example. If
you are willing to take the code in the new method on trust, then skip to the next “Try It Out” section. On the
other hand, you shouldn't find it too difficult if you can still remember what you did in high school math.
One way to get the intersection of two lines is to use equations such as those shown in Figure 5-8 . These
are called parametric equations because they use a parameter value ( s or t ) as the variable for determining
points on each line. The parameters s and t vary between 0 and 1 to give points on the lines between the
defined start and end points. When a parameter s or t is 0 the equations give the coordinates of the start point
of a line, and when the parameter value is 1 you get the end point of the line.
Where two lines intersect, the equations for the lines must produce the same ( x , y ) values, so, at this point,
the right-hand sides of the equations for x for the two lines must be equal, and the same goes for the equa-
tions for y . This gives you two equations in s and t , and with a bit of algebraic juggling you can eliminate s
to get the equation shown for t . You can then replace t in the equations, defining line 1 to get x and y for the
intersection point.
TRY IT OUT: Calculating the Intersection of Two Lines
You can use these results to write the additional method you need in the Line class. Add the following
code to the class definition in Line.java :
 
 
Search WWH ::




Custom Search