如何使用 dist() 函数计算 5 个点之间的距离?

how can i calculate the distances between 5 points using the dist() function?

dist()计算两点之间的距离,但是我想计算5个点之间的距离(圆上的点和矩形中的四个点(每个角都有一个点)之间的距离) ) 我该怎么做?

intersects(other){

    let di =  dist(this.x, this.y, other.x, other.y)
    let di2 =  dist(this.x, this.y, other.x + 80, other.y)
    let di3 =  dist(this.x, this.y, other.x, other.y + 150)
    let di4 =  dist(this.x, this.y, other.x + 80, other.y + 150)
    if (di && di2 && di3 && di4 <= this.r) {
        return true;
    } else {
        return false;
    }
}

我试图硬编码它,但 if 函数只使用 "di4"

如果你想验证是否所有距离都低于某个阈值,那么你必须将所有值与参考距离进行比较,并通过 &&:

if (di <= this.r && di2 <= this.r && di3 <= this.r && di4 <= this.r) {
    // [...]
}

如果您想验证是否有任何距离低于 特定阈值,那么您必须将所有值与参考距离进行比较,并通过以下方式连接结果||:

if (di <= this.r || di2 <= this.r || di3 <= this.r || di4 <= this.r) {
    // [...]
}

如果要获取值列表中的最大值,则可以使用 max() 函数。如果所有距离都低于this.r:

,这等于评估
if (max([di, di2, di3, di4]) <= this.r) {
   // [...]
}

如果要获取值列表中的最小值,则可以使用 min() 函数。如果任何距离低于 this.r:

,则这等于评估
if (min([di, di2, di3, di4]) <= this.r) {
   // [...]
}

注意,表达式

di && di2 && di3 && di4 <= this.r

没有按照您的预期去做。只有 d14this.r 进行比较。如果其他项未定义并且值不等于 0.0.
,则其他项的计算结果为 true 这意味着表达式可以读作 di != 0 && di2 != 0 && di3 != 0 && di4 <= this.r


但是请注意,如果你想验证一个圆是否完全在矩形内,那么你必须验证圆到每一边(而不是角点)的距离是否在上方(而不是下方)圆的半径:

intersects(other){

    let di  =  this.x - other.x;       // distance to the left 
    let di2 =  other.x + 80 - this.x;  // distance to the right
    let di3 =  this.y - other.y;       // distance to the top
    let di4 =  other.y + 150 - this.y; // distance to the bottom
    if (di >= this.r && di2 >= this.r && di3 >= this.r && di4 >= this.r) {
        return false;
    } else {
        return true;
    }
}

如果你也想验证到矩形中心的距离,那么你必须通过 dist() 来计算到中心的距离。
因此,如果您想验证圆是否到达中心点或矩形的任何一侧,那么您必须检查是否有任何距离低于半径

let di  =  this.x - other.x;       // distance to the left 
let di2 =  other.x + 80 - this.x;  // distance to the right
let di3 =  this.y - other.y;       // distance to the top
let di4 =  other.y + 150 - this.y; // distance to the bottom

// distance to the center point
let di5 = dist(this.x, this.y, other.x + 80/2, other.y + 150/2);

if (di <= this.r || di2 <= this.r || di3 <= this.r && di4 <= this.r && di5 <= this.r) {
    // [...]
}

if (min([di, di2, di3, di4, di5]) <= this.r) {
    // [...]
}