簡體   English   中英

如何使用dist()函數計算5點之間的距離?

[英]how can i calculate the distance 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 

沒有做你期望它做的事。 只有d14相比this.r 如果未定義的其他術語評估為true則值不等於0.0。
這意味着表達式可以讀作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) {
    // [...]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM