In this simple program, we animate an ellipse to always chase a point defined by the mouse. The ellipse only ever moves a percentage of the distance between it and the target destination in each step. The p5.Vector object is used to handle the coordinates and the simple math operations.
var pos; var targetPos; var mousePos; function setup() { createCanvas(1000, 600); fill(0); pos = createVector(0, 0); targetPos = createVector(0, 0); mousePos = createVector(width/2, height/2); } function draw() { background(255); targetPos.set(mousePos); targetPos.sub(pos); // find the vector between mouse position and ellipse position targetPos.mult(0.2); // each step in the animation will move this percentage of the distance to the target position pos.add(targetPos); ellipse(pos.x, pos.y, 60, 60); } function mousePressed() { mousePos.set(mouseX, mouseY); } |
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); } } |
Solution using a class.