I'm trying to make a circle move to another circle. So far I have it changing it x and y positions until they equal the x and y of the other circle, but this ends up looking weird and often they will equal one of the variables sooner than the other and will move in straight line to it. What I want it to do is move in a diagonal line straight towards it. How could I do this?
One way you could do this is using Vectors. This has some upsides such as it working at (almost) any position and easily adjustable speeds. This also might come in handy if the project gets more complex. However, it does take up more space and isn't as tidy.
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>