php查找点和线段的距离而不是二维线 [英] php find distance of a point and a line segment not a line in 2D

查看:221
本文介绍了php查找点和线段的距离而不是二维线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一条直线的两个点,例如p1(a,b)和p2(c,d) 我的意思是X(x,y)

I have two point of a line like p1(a,b) and p2(c,d) my point is X(x,y)

我已经搜索并找到了此处

但不是php 谁能帮我

but it isn't php can anyone help me

推荐答案

免责声明:我假定来自链接答案的JS代码.

DISCLAIMER: I assumed the JS code from the linked answer works.

下面是我试图将此处中的javascript代码转换为PHP.

Below is my attempt to convert the javascript code from here to PHP.

function sqr($x) { return $x * $x; }
function dist2($v, $w) { return sqr($v->x - $w->x) + sqr($v->y - $w->y); }
function distToSegmentSquared($p, $v, $w) {
    $l2 = dist2($v, $w);
    if ($l2 == 0) return dist2($p, $v);
    $t = (($p->x - $v->x) * ($w->x - $v->x) + ($p->y - $v->y) * ($w->y - $v->y)) / $l2;
    $t = max(0, min(1, $t));
    return dist2($p, (object) array('x' => $v->x + $t * ($w->x - $v->x),
                    'y' => $v->y + $t * ($w->y - $v->y) ));
}
function distToSegment($p, $v, $w) { return sqrt(distToSegmentSquared($p, $v, $w)); }

像这样使用它:

$p = (object) array('x' => 2, 'y' => 2);
$v = (object) array('x' => 9, 'y' => 2);
$w = (object) array('x' => 2, 'y' => 9);

echo distToSegment($p, $v, $w);





比较JS输出和PHP输出:

Comparing JS output with PHP output:

测试1

对于

x = {x:2, y:2}
v = {x:9, y:2}
w = {x:2, y:9}

JS输出:

4.949747468305833

4.949747468305833

PHP输出:

4.9497474683058

4.9497474683058


测试2

对于

x = {x:1, y:9}
v = {x:4, y:4}
w = {x:4, y:9}

JS输出:

3

PHP输出:

3


测试3

对于

x = {x:5, y:6}
v = {x:2, y:9}
w = {x:8, y:2}

JS输出:

0.32539568672798375

0.32539568672798375

PHP输出:

0.32539568672798

0.32539568672798

这篇关于php查找点和线段的距离而不是二维线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆