Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

math - PHP Find Coordinates between two points

simple question here. Lets say I have two points:

point 1

x = 0
y = 0


point 2

x = 10
y = 10

How would i find out all the coordinates inbetween that programmatically, assuming there is a strait line between two points... so the above example would return:

0,0
1,1
2,2
3,3
...
8,8
9,9
10,10

Thanks :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to find the slope of the line first:

m = (y1 - y2) / (x1 - x2)

Then you need to find the equation of the line:

y = mx + b

In your example you we get:

y = 1x + b
0 = 1(0) + b

or

y = x

To get all of the coordinates you simply need to plug in all values x1 -> x2. In PHP this entire thing looks something like:

// These are in the form array(x_cord, y_cord)
$pt1 = array(0, 0);
$pt2 = array(10, 10);
$m = ($pt1[1] - $pt2[1]) / ($pt1[0] - $pt2[0]);
$b = $pt1[1] - $m * $pt1[0];

for ($i = $pt1[0]; $i <= $pt2[0]; $i++)
    $points[] = array($i, $m * $i + $b);

This will of course give you the coordinates for all points that fall on integer values of X, and not "all coordinates" between the two points.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...