Renjith
Renjith

Reputation: 524

How to find a point in a line in java?

I am trying to do some experiments with path. I have two points (x0,y0) and (x2,y2). Now I have to find a point (x1,y1) that should be some distance from the final point (x2,y2).

For example
Start Point (0,0) End Point (0,5)
Point i want to find is (0,2)

enter image description here

Upvotes: 1

Views: 2239

Answers (3)

Ali Seify
Ali Seify

Reputation: 39

/* I used @user3235832 formula and write this code and its solve my problem.
Code in java.
sourcePoint(x,y);
destinationPoint(w,h);*/
//--------------------------------------------------------------------
double l = Math.sqrt(Math.pow((w - x), 2) + Math.pow((h - y), 2));
double d = l / 10;//you can use your own value for d.
int newX = (int) (w + (((x - w) / (l) * d)));
int newy = (int) (h + (((y - h) / (l) * d)));
//--------------------------------------------------------------------
/* if you use like me Graphic2D and use g2d.fillOval() function for draw a oval 
on the line you need line slop. code for this: */
double m = Double.POSITIVE_INFINITY;//line slop
if (w - x != 0) {
    m = (h - y) / (w - x);
}
int r = 6;//size of Oval
if (m == 0) {
    g2d.fillOval(newX, (newy - (r/2)), r, r);
} else if (m == Double.POSITIVE_INFINITY) {
    g2d.fillOval((newX - (r/2)), newy, r, r);
} else if (m < 0) {
    g2d.fillOval((newX - (r/2)), (newy - (r/2)), r, r);
} else {
    g2d.fillOval(newX, newy, r, r);
}

Upvotes: 0

Bruno Negr&#227;o Zica
Bruno Negr&#227;o Zica

Reputation: 814

Imagine the two points define two rectangle triangles. The bigger triangle has sides with sizes x1, y1. the smaller has sides of sizes xt, yt.

1) Now apply Pythagoras' Theorem two calculate the bigger hypotenuse, h, using the equation h^2 = x1^2 + y1^2; (where h^2 means h power of two)

2) the difference ( h - the distance) is the hypotenuse of the smaller triangle. let's call it ht.

3) Calculate xt and yt as directly proportional to hypot bigger/hypot smaller. x1/xt = h/ht y1/yt = h/ht

Upvotes: 0

user3235832
user3235832

Reputation:

For a line between

enter image description here

The point at distance d from the first point, (positive) in the direction of the second point, is given by:

enter image description here

Where L is the distance between the two points defining the line:

enter image description here

(For your case just take L - d instead of d)

Upvotes: 2

Related Questions