Search code examples
phpvector3d

How to get an Array of points between 2 3d vectors


Im looking for a way to get an array of points between 2 points that are 3d.

What I’ve found

So far while looking ive not found anything that is 3d, when I look for 3d it only returns a bunch of things of How to get distance between 2 points And thats not what im looking for!

I have found 1 good one about 2d points - here

However Ive found nothing about 3d, so sorry if this is duplicate.

Ive also tried search Stack Exchange Mathematics, and multiple other webpages, and still cant find anything that can answer my question.

More Details

Im going to give an example so that its more clear what I am looking for. Say I have 2 3d vectors (x1, y1, z1) and (x2, y2, z2). My points in this example will be (0, 0, 0) and (10, 10, 10).

After I have run these through the function I would want it to return an array of points something like this:

[1, 1, 1],
[2, 2, 2],
[3, 3, 3]

All the way up to 10.


Solution

  • Answer

    I have now found the answer to my question above.

    function logPointsOnLine(array $point1, array $point2, int $points) {
    
      $vecs = [];
      
      $delX = $point2[0] - $point1[0];
      $delY = $point2[1] - $point1[1];
      $delZ = $point2[2] - $point1[2];
    
      for($i = 0; $i < $points; $i++) {
        $newX = $point1[0] + $delX / ($points - 1) * $i;
        $newY = $point1[1] + $delY / ($points - 1) * $i;
        $newZ = $point1[2] + $delZ / ($points - 1) * $i;
        array_push($vecs, array($newX, $newY, $newZ));
      }
    }
    

    If you want to run it one way you could do it is:

    $vec1 = array(10, 12, 32);
    $vec2 = array(15, 60, 25);
    $amt = 10;
    
    $points = logPointsOnLine($vec1, $vec2, $amt);
    
    print_r($points);