簡體   English   中英

如何使 object 在 p5js 中移動到另一個 object?

[英]How to make an object move to another object in p5js?

我試圖讓一個圈子移動到另一個圈子。 到目前為止,我讓它改變它的 x 和 y 位置,直到它們等於另一個圓的 x 和 y,但這最終看起來很奇怪,而且它們通常會比另一個變量更快地等於一個變量,並且會直線移動到它. 我想要它做的是沿對角線直線向它移動。 我怎么能這樣做?

你可以做到這一點的一種方法是使用向量。 這有一些好處,例如它(幾乎)可以在任何 position 上工作,並且速度易於調節。 如果項目變得更復雜,這也可能會派上用場。 但是,它確實占用更多空間並且不那么整潔。

 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 -= mx * d; y2 -= my * 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>

要將一個圓圈移向另一個圓圈,您可以將其沿兩個圓圈之間的線移動。

看看這個草圖,看看當鼠標按下時第二個圓圈的 position 是如何更新的。

 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>

暫無
暫無

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

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