當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


p5.js dist()用法及代碼示例

dist()函數以2D或3D計算歐幾裏得距離。表示p5.js | dist()函數用於測量2D或3D中兩點之間的距離。以下是2D和3D中距離的公式。

  • 2D公式:
      d = \sqrt{(x_1-x_2)^2+(y_1-y_2)^2}
  • 3D公式:
      d = \sqrt{(x_1-x_2)^2+(y_1-y_2)^2+(z_1-z_2)^2}

用法:

dist(x1, y1, x2, y2)
dist(x1, y1, z1, x2, y2, z2)

參數:


  • x1:這些參數保存第一個點的x坐標。
  • y1:這些參數保存第一個點的y坐標。
  • z1:這些參數保留第一個點的z坐標。
  • x2:這些參數保留第二點的x坐標。
  • y2:這些參數保留第二點的y坐標。
  • z2:這些參數保留第二個點的z坐標。

返回值:兩點之間的距離。
例:本示例計算並打印固定點和光標之間的距離。

function setup() { 
    // Create a canvas 
    createCanvas(400, 400); 
} 
  
function draw() { 
    // set background color 
    background(50); 
    // coordinates of the fixed point 
    var x1 = 200; 
    var y1 = 200; 
    // coordinates of the cursor 
    var x2 = mouseX; 
    var y2 = mouseY; 
    // set line color and weight 
    stroke(255); 
    strokeWeight(2); 
    // draw a line connecting 2 points 
    line(x1, y1, x2, y2); 
    fill("red"); 
    // draw a circle centered at each point 
    ellipse(x1, y1, 10); 
    ellipse(x2, y2, 10); 
    // calculate the distance between 2 points 
    d = dist(x1, y1, x2, y2); 
    noStroke(); 
    fill("lightgreen"); 
    // set text size and alignment 
    textSize(20); 
    textAlign(CENTER); 
    // display the distance calculated 
    text("distance = "+ str(d), 200, 350); 
}

輸出:

在線編輯:
環境設置:

參考: https://p5js.org/reference/#/p5/dist



相關用法


注:本文由純淨天空篩選整理自SujanDutta大神的英文原創作品 p5.js | dist() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。