Versions Compared

Key

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

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 PVector  The p5.Vector object is used to handle the coordinates and the simple math operations.

PVector
Code Block
languagejs
linenumberstrue
var pos;
PVectorvar targetPos;
PVectorvar mousePos;

voidfunction setup() {
  sizecreateCanvas(1000, 600);
  fill(0);
  pos = new PVectorcreateVector(0, 0);
  targetPos = new PVectorcreateVector(0, 0);
  mousePos = new PVectorcreateVector(width/2, height/2);
}

voidfunction 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);
}
void
function mousePressed() {
  mousePos.set(mouseX, mouseY);
};

...


Exercise 

  1. Add an additional ellipse that follows the mouse at a slower rate than the first ellipse. 
  2. Modify the code so that the ellipse always follows the mouse position.  
  3. Replace with the ellipse with another shape (like a triangle or even a car) , and keep it pointed towards the mouse.

Exercise Solution Using Arrays

Code Block
languagejs
linenumberstrue
collapsetrue
PVector[]var pos; = PVector[];
var targetPos = [];
PVectorvar mousePos = [];
intvar arrayLength = 5;
void
function setup() {
  sizecreateCanvas(1000, 600);
  fill(0);
   pos = new PVector[arrayLength];
  targetPos = new PVector[arrayLength];

  for (intvar i = 0; i<pos.lengthi< arrayLength; i++) { 
    pos[i] = new PVectorcreateVector(0, 0);
    targetPos[i] = new PVectorcreateVector(0, 0);
  }
   mousePos = new PVectorcreateVector(width/2, height/2);
}

voidfunction draw() {
    mousePos.set(mouseX, mouseY);
   background(255);
 
  
  for (intvar i = 0; i i<pos< 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.0205); // 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. 

classExample.zip

...