Code Behaving Differently When Inside Function

I’ve been trying to create a sketch that moves a shape towards the mouse and then returns to a given starting point. This sketch does what I want with one shape but I want to have multiple shapes beginning from different starting points on the canvas.

https://editor.p5js.org/PaulMaguire/sketches/LuNgbCiD8

I created a new sketch where I put the code into a function called “arrow”, hoping to call it multiple times, creating other shapes with different starting points, all moving towards the mouse.

https://editor.p5js.org/PaulMaguire/sketches/dgQojf22u

As you can see from the links, in the second sketch the shapes no longer move towards the mouse.
I was wondering why this is? The values used are the same, perhaps it has something to do with where the mouse position is referred to in the order of execution?
Any light you could shed on this would be really helpful.
Thanks!

1 Like

i don’t think your arrow function is actually changing the x1 y1 vars. it might prove worthwhile packing what you want into a class something like the code below.

var chaser;

function setup() {
  createCanvas(720, 400);
  noStroke();
  
  chaser = new Chaser(width / 2, height / 2, 0.1);
}

function draw() {
  background(237, 34, 93);
  
  chaser.chase(mouseX, mouseY);
  chaser.present();
}

class Chaser{
  constructor(x, y, easing) {
    this.ox = x;
    this.oy = y;
    this.x = x;
    this.y = y;
    this.easing = easing;
  }
  chase(targetX, targetY) {
    var dx = targetX - this.x;
    var dy = targetY - this.y;
    var dist = sqrt(dx * dx + dy * dy);
    if(dist > 32) {
      this.x += dx * this.easing;
      this.y += dy * this.easing;
    }
    else {
      this.x = this.ox;
      this.y = this.oy;
    }
  }
  present() {
    fill(255);
    ellipse(this.x, this.y, 64);
  }
}
1 Like

Thanks hotfooted, I’m learning a lot just looking through your code, very helpful