Java Program to Find Direction of a Point from a Line Segment
import java.awt.Point;
import java.util.Scanner;
import static java.lang.Math.*;
public class Main
{
// Static constant values
static int RIGHT = 1, LEFT = -1, ZERO = 0;
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
//Coordinates of the line
Point a = new Point(-30,10);
Point b = new Point(29,-15);
//Coordinates of the line
Point p = new Point(15,28);
// Calls the function to find the direction of point w.r.t. the line segment
int dir = pointDirection(a,b,p);
if (dir == 1)
System.out.println("Point is towards the right of the line");
else if (dir == -1)
System.out.println("Point is towards the left of the line");
else
System.out.println("Point is on the Line");
}
// Function to calculate direction of the point from the line segment
static int pointDirection(Point A, Point B, Point P)
{
// Subtracting the coordinates of the first point
// from the rest points to make A origin
B.x -= A.x;
B.y -= A.y;
P.x -= A.x;
P.y -= A.y;
//Cross product formula
int crossPro = B.x * P.y - B.y * P.x;
// Returns zero,right or left based on the sign of the crossproduct
if (crossPro > 0)
return RIGHT;
if (crossPro < 0)
return LEFT;
return ZERO;
}
}
Output:
Point is towards the right of the line
