Gavin C.
Gavin C.

Reputation: 105

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

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?

Upvotes: 0

Views: 2386

Answers (2)

Henhen1227
Henhen1227

Reputation: 412

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/[email protected]/lib/p5.js"></script>

Upvotes: 5

Charlie Wallace
Charlie Wallace

Reputation: 1830

To move a circle towards another circle you can move it along the line between the two circles.

Take a look at this sketch and see how the second circle's position is updated when the mouse is down.

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/[email protected]/lib/p5.js"></script>

Upvotes: 0

Related Questions