Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, Generate a direct path of points between two points

Tags:

java

path

point

I currently have a bad method for doing this, it just translates the start point by 1/-1 depending on if the x/y coordinate is over or under the current coordinates and adds it to an ArrayList until the start point .equals(end), this is a bad solution because it creates a really bad path that looks like the black path below.

https://dl.dropbox.com/u/64681860/paths.png

I'm trying to generate a direct path of points between two points (The same kind of line as Graphics.drawLine makes).

I'm guessing I need to use the Math class to get the angle, but I'm not very familiar with the Math API.

like image 209
Caleb Avatar asked Feb 27 '26 12:02

Caleb


1 Answers

One somewhat naive way, is to work out the ratio of the slope, rather than the angle.

Something like:

float ratio = (y2 - y1) / (x2 - x1);

Then:

width = x2 - x1;
for(int i = 0; i < width; i++) {
    float x = x1 + i;
    float y = y1 + (ratio * i);
    points.add(new Point(x,y));
}

If float isn't what you need, you'll need to do some conversion.

You'll also need to handle the special case of x1 == x2, or you'll get divide-by-zero errors.

Using this method, the steeper the line, the fewer points you will generate. If you want the points evenly spaced no matter what the angle, you'll need to break out sin/cos/tan.

Write unit tests for lines in at least the main 8 compass directions, to iron out any glitches.

like image 155
slim Avatar answered Mar 01 '26 02:03

slim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!