限制一行的长度 [英] Limit the length of a line
问题描述
我正在尝试绘制一条表示弹弓"的线,并且希望它具有最大的绘制长度.
I'm trying to draw a line that represents a 'slingshot' and I want it to have a maximum draw length.
在p5中,我在positionA和positionB之间画了一条线:
in p5 I'm drawing a line between positionA and positionB:
line(posA.x, posA.y, posB.x, posB.y);
posA是鼠标x和y. posB是圆在画布上的位置.
posA is the mouse x and y. posB is the position of a circle on the canvas.
我想做的是限制行的长度,以使它的长度永远不会超过40像素,但仍要从圆上指向鼠标.
What I want to do is limit the length of the line, so that it is never more than 40px long, but still points toward the mouse from the circle.
推荐答案
欧几里德距离 sqrt(dx*dx + dy*dy)
计算2点之间的距离.
如果将一个点的向量除以另一个点的长度,则会得到单位向量长度为1.
The Euclidean distance between 2 points is calculated by sqrt(dx*dx + dy*dy)
.
If you divide the vector of one point to the other by its length then you get the Unit vector with length 1.
计算从posA
到posB
的单位矢量,并将其乘以40:
Calculate the unit vector from posA
to posB
and multiply it by 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
进行所有这些计算.
In p5.js you can use p5.Vector
for all this calculations.
-
.sub()
减去两点并计算向量 -
.normalize()
计算长度为1的单位矢量 -
.mult()
缩放矢量 -
.add()
将矢量添加到该点
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>
这篇关于限制一行的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!