Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagejs
linenumberstrue
collapsetrue
var pos = [];
var targetPos = [];
var mousePos = [];
var arrayLength = 5;

function setup() {
  createCanvas(1000, 600);
  fill(0);
  for (var i = 0; i< arrayLength; i++) { 
    pos[i] = createVector(0, 0);
    targetPos[i] = createVector(0, 0);
  }
   mousePos = createVector(width/2, height/2);
}

function draw() {
   mousePos.set(mouseX, mouseY);
   background(255);
  
  for (var i = 0; i < pos.length; i++) { 
        targetPos[i].set(mousePos); 
        targetPos[i].sub(pos[i]);  // find the vector between mouse position and ellipse position
        targetPos[i].mult((i*0.02) + 0.05); // each step in the animation will move this percentage of the distance to the target position
        pos[i].add(targetPos[i]);
        fill(125,255,23);
        ellipse(pos[i].x, pos[i].y, 60, 60);
    }
}

...


Exercise Solution Using Arrays and Classes

Code Block
languagejs
linenumberstrue
collapsetrue
let shape = [];
var arrayLength = 60;


function setup() {
  createCanvas(1000, 600);
  fill(0);

  for (var i= 0; i < arrayLength; i++) {
    shape[i] = new myShape((i*0.02) + 0.02);
  }
}

function draw() {
  background(255);
  for (var i= 0; i < shape.length; i++) {
    shape[i].update();
  }
}

class myShape {
  
  constructor(_speed) {
   this.pos = createVector(0,0);
   this.targetPos = createVector(0,0);
   this.mousePos = createVector(width/2, height/2);
   this.speed = _speed;
  }
  

  update() {
    this.mousePos.set(mouseX, mouseY);
    this.targetPos.set(this.mousePos); 
    this.targetPos.sub(this.pos);  // find the vector between mouse position and ellipse position
    this.targetPos.mult(this.speed); // each step in the animation will move this percentage of the distance to the target position
    this.pos.add(this.targetPos);
    
    pushMatrix();
    translate(this.pos.x, this.pos.y);
    rotate(calcAngle(this.pos, this.mousePos));
    triangle(0,0,-5,20,5,20);
    popMatrix();
  }

  calcAngle(p1, p2)
  {
    return -atan2(p1.x - p2.x,p1.y - p2.y);
  }
}

...