如何让一个对象移动到p5js中的另一个对象?
How to make an object move to another object in p5js?
我正在尝试让一个圈子移动到另一个圈子。到目前为止,我已经改变了它的 x 和 y 位置,直到它们等于另一个圆的 x 和 y,但这最终看起来很奇怪,而且它们通常会比另一个变量更快地等于一个变量,并且会直线移动到它.我想让它做的是沿对角线直线朝它移动。我该怎么做?
要将一个圆移向另一个圆,您可以沿着两个圆之间的线移动它。
看看这个草图,看看当鼠标按下时第二个圆的位置是如何更新的。
let angle = 0;
let x1 = 25;
let y1 = 25;
let x2 = 350;
let y2 = 350
let d = 0.025;
function setup() {
createCanvas(400, 400);
}
function draw() {
background(0);
stroke(255);
strokeWeight(4);
let r = 20;
circle(x1, y1, r);
circle(x2, y2, r);
if(mouseIsPressed){
x2 = (1-d)*x2-d*(x1+x2);
y2 = (1-d)*y2-d*(y1+y2);
}
}
<script src="https://cdn.jsdelivr.net/npm/p5@1.3.0/lib/p5.js"></script>
实现此目的的一种方法是使用向量。这有一些好处,例如它可以(几乎)在任何位置工作并且可以轻松调节速度。如果项目变得更加复杂,这也可能会派上用场。但是,它确实占用了更多 space 并且不够整洁。
let x1 = 25;
let y1 = 25;
let x2 = 350;
let y2 = 350;
let d = 5;
function setup() {
createCanvas(400, 400);
}
function draw() {
background(0);
stroke(255);
strokeWeight(4);
let r = 20;
circle(x1, y1, r);
circle(x2, y2, r);
if (mouseIsPressed) {
//Create a vector of the distance between them
var m = createVector(x2 - x1, y2 - y1);
//This sets the magnitude so that it moves in a constant rate but in the right direction.
m.normalize();
//Set d equal to the speed
x2 -= m.x * d;
y2 -= m.y * d;
}
}
//So that circle1 can move around
function mouseDragged() {
x1 = mouseX;
y1 = mouseY;
}
<script src="https://cdn.jsdelivr.net/npm/p5@1.3.0/lib/p5.js"></script>
我正在尝试让一个圈子移动到另一个圈子。到目前为止,我已经改变了它的 x 和 y 位置,直到它们等于另一个圆的 x 和 y,但这最终看起来很奇怪,而且它们通常会比另一个变量更快地等于一个变量,并且会直线移动到它.我想让它做的是沿对角线直线朝它移动。我该怎么做?
要将一个圆移向另一个圆,您可以沿着两个圆之间的线移动它。
看看这个草图,看看当鼠标按下时第二个圆的位置是如何更新的。
let angle = 0;
let x1 = 25;
let y1 = 25;
let x2 = 350;
let y2 = 350
let d = 0.025;
function setup() {
createCanvas(400, 400);
}
function draw() {
background(0);
stroke(255);
strokeWeight(4);
let r = 20;
circle(x1, y1, r);
circle(x2, y2, r);
if(mouseIsPressed){
x2 = (1-d)*x2-d*(x1+x2);
y2 = (1-d)*y2-d*(y1+y2);
}
}
<script src="https://cdn.jsdelivr.net/npm/p5@1.3.0/lib/p5.js"></script>
实现此目的的一种方法是使用向量。这有一些好处,例如它可以(几乎)在任何位置工作并且可以轻松调节速度。如果项目变得更加复杂,这也可能会派上用场。但是,它确实占用了更多 space 并且不够整洁。
let x1 = 25;
let y1 = 25;
let x2 = 350;
let y2 = 350;
let d = 5;
function setup() {
createCanvas(400, 400);
}
function draw() {
background(0);
stroke(255);
strokeWeight(4);
let r = 20;
circle(x1, y1, r);
circle(x2, y2, r);
if (mouseIsPressed) {
//Create a vector of the distance between them
var m = createVector(x2 - x1, y2 - y1);
//This sets the magnitude so that it moves in a constant rate but in the right direction.
m.normalize();
//Set d equal to the speed
x2 -= m.x * d;
y2 -= m.y * d;
}
}
//So that circle1 can move around
function mouseDragged() {
x1 = mouseX;
y1 = mouseY;
}
<script src="https://cdn.jsdelivr.net/npm/p5@1.3.0/lib/p5.js"></script>