Wednesday, 02 October 2019

Finding the Middle Point of a Line Segment

PHP 

The vector operations are often used in 3D programming. For example, given a line segment with the start point, \(P_1\), and the end point, \(P_2\), it is easy to find the point \(P\) along the line segment \(P_1\)\(P_2\) at the distance \(d\) away from \(P_1\) by using the vector operations. First, we get the vector \(\vec{v}=P_2-P_1\). The unit vector of \(\vec{v}\) is \(\hat{u}=\frac{\vec{v}}{\|\vec{v}\|}\). Then we can get the point \(P\) as \(P=P_1+d\hat{u}\). By using this way, we can easily find the points that divide a line segment into equal parts.

The following codes define the function getPoints($p1, $p2, $parts) that gets all the points that divide a line segment into equal parts regarding the start point $p1, the end point $p2 and the amount of equal parts $parts as we want.

require_once 'SimpleVector3D.php';

use CodeBilby\SimpleVector3D;

function getPoints($p1, $p2, $parts) 
{
    $v = $p2->sub($p1);
    $len = $v->len();
    $norm = $v->normalize();

    $array = array($p1);

    $subsegment = $len / $parts;

    for ($i = 1; $i < $parts; $i ++) {
        $point = $p1->add($norm->scale($subsegment * $i));
        array_push($array, $point);
    }

    array_push($array, $p2);

    return $array;
}

In line 1, we use the SimpleVector3D class posted in A Simple 3D Vector Class in PHP for vector operations. From line 7 to 9, we get the unit vector $norm of $v. The length of the subsegment $subsegment is got in line 13. From line 15 to 18, we can get all the points based on the way we discussed.


We can use the function getPoints($p1, $p2, $parts) like this:

$p1 = new SimpleVector3D([10, 20, 30]);
$p2 = new SimpleVector3D([190, 10, -40]);
$parts = 5;

$array = getPoints($p1, $p2, $parts);

echo 'Amount of parts: ' . $parts. '<br>';
for ($i = 0; $i < count($array); $i++) {
    echo $array[$i]->toString().'<br>';
}

From line 1 to 3, we define the start point $p1, the end point $p2 and the amount of the subsegments we want. The function getPoints($p1, $p2, $parts) is called in line 5. Finally, from line 7 to 10, the details of the returned points are printed out.

The output will be:

Amount of parts: 5
[10, 20, 30]
[46, 18, 16]
[82, 16, 2]
[118, 14, -12]
[154, 12, -26]
[190, 10, -40]


Search