How to make an object move to another object in p5js?

Gav*_* C. 0 javascript p5.js

我试图让一个圆圈移动到另一个圆圈。到目前为止,我已经改变了它的x和y位置,直到它们等于另一个圆的x和y,但这最终看起来很奇怪,通常它们会比另一个变量更早等于其中一个变量,并且会直线移动到它。我想要它做的是沿对角线笔直朝它移动。我怎么能这样做呢?

Hen*_*227 5

实现此目的的一种方法是使用向量。这有一些优点,例如它可以在(几乎)任何位置工作并且可以轻松调节速度。如果项目变得更加复杂,这也可能会派上用场。然而,它确实占用了更多空间,而且不那么整洁。

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;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.jsdelivr.net/npm/p5@1.3.0/lib/p5.js"></script>
Run Code Online (Sandbox Code Playgroud)