【问题标题】:Limit the length of a line限制线的长度
【发布时间】:2019-06-06 21:36:42
【问题描述】:

我正在尝试绘制一条代表“弹弓”的线,并且我希望它具有最大拉距。

在 p5 中,我在 positionA 和 positionB 之间画了一条线:

line(posA.x, posA.y, posB.x, posB.y);

posA 是鼠标 x 和 y。 posB 是画布上圆的位置。

我想要做的是限制线的长度,使其长度永远不会超过 40px,但仍然从圆圈指向鼠标。

【问题讨论】:

  • 您需要计算两点之间的距离。如果它太长,那么你需要找到点A和B之间向量的角度,然后找到距离B点沿该角度40px的点。

标签: javascript canvas processing p5.js


【解决方案1】:

2 点之间的Euclidean distancesqrt(dx*dx + dy*dy) 计算。 如果将一个点的向量除以另一个点的长度,则得到长度为 1 的 Unit vector

计算从posAposB的单位向量并乘以40:

// (dx, dy): vector form "posA" to "posB" 
let dx = posB.x-posA.x;
let dy = posB.y-posA.y;

// dist : euclidean distance, length of the vecotr 
let dist = Math.sqrt(dx*dx + dy*dy);

// (ux, uy): unit vector form 'posA' in direction to 'posB', with length 1 
let ux = dx / dist;
let uy = dy / dist;

// (x2, y2): point with a distance of 40 from "posA" an the vector to "posB"
let x2 = posA.x + ux * 40;
let y2 = posA.y + uy * 40;

line(posA.x, posA.y, x2, y2);

在 p5.js 中,您可以使用 p5.Vector 进行所有这些计算。

let A = createVector(posA.x, posA.y);
let B = createVector(posB.x, posB.y);

let P = B.sub(A).normalize().mult(40).add(A);
line(posA.x, posA.y, P.x, P.y);

看例子:

function setup() {
    createCanvas(200, 200);
}

function draw() {

    background(0, 0, 0);
    stroke(255, 0, 0);
    strokeWeight(5);

    let A = createVector(width/2, height/2);
    let B = createVector(mouseX, mouseY);

    let P = B.sub(A).normalize().mult(40).add(A);
    line(A.x, A.y, P.x, P.y);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script>

【讨论】:

  • 这太棒了,我特别喜欢它包括数学和 p5 方式。我还没有尝试过第一部分,但是 p5 的线条画表现得很奇怪。我正在记录 A 和 B 的位置,它们是 A:241 348,B:249 360。但是这条线从我的鼠标拉到左上角的某个地方,有时在屏幕外。
  • 鼠标是posA,圆圈是posB
  • @Ashbury 所以你必须计算A.sub(B).normalize().mult(40)
  • 对不起,我仍然得到相同的结果交换 A.sub(B) 以下是值:A:x:375 y:216 B:x:249 y:360 P:x:- 26 岁:30
  • @Ashbury 抱歉,我忘记将向量添加到 A。我已更正了答案。我在解释部分做了,但我没有在 p5.Vector (2nd) 部分
猜你喜欢
  • 2013-10-25
  • 2010-12-06
  • 1970-01-01
  • 1970-01-01
  • 2016-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多