Search code examples
algorithmprocessingeasing

Easing trail with sine algorithms in Processing


Here is my source code:

int index;
int num = 60;
float mx[] = new float[num];
float my[] = new float[num];
float explosion;
float x;
float y;
float px;
float py;
float xold;
float yold;
float xplode1;
float yplode1;
float xplode2;
float yplode2;
float xplode3;
float yplode3;
float xplode4;
float yplode4;
float easing = 0.05;

void setup() {
  size(1366, 768);
  noStroke();
//  noFill();
  fill(25, 155);
}

void draw() {
  int which = frameCount % num;
  
  explosion = explosion + 0.32;
  background(92, 55, 169);

  float targetX = mouseX;
  float dx = targetX - px;
  float lx = targetX - x;
  if (abs(dx) > 1) {
    mx[which] += dx * easing;
    x += lx * easing;
    if (mousePressed && (mouseButton == LEFT)) {
      xplode1 = dx + 50 + sin(explosion)*30;
      xplode2 = dx + 50 + sin(explosion)*30;
      xplode3 = dx - 50 - sin(explosion)*30;
      xplode4 = dx - 50 - sin(explosion)*30;
    }
    else {
      xplode1 = -10;
      xplode2 = -10;
      xplode3 = -10;
      xplode4 = -10;
    }
  }

  float targetY = mouseY;
  float dy = targetY - py;
  float ly = targetY - y;
  if (abs(dy) > 1) {
    my[which] += dy * easing;
    y += dy * easing;
    if (mousePressed && (mouseButton == LEFT)) {
      yplode1 = dy + 50 + sin(explosion)*30;
      yplode2 = dy - 50 - sin(explosion)*30;
      yplode3 = dy - 50 - sin(explosion)*30;
      yplode4 = dy + 50 + sin(explosion)*30;
    }
    else {
      yplode1 = -10;
      yplode2 = -10;
      yplode3 = -10;
      yplode4 = -10;
    }
  }
  
  for(int i = 0;i<num;i++){
    index = (which + 1 + i) % num;
    ellipse(mx[index], my[index], i, i);
  }
  ellipse(xplode1, yplode1, 10, 10);
  ellipse(xplode2, yplode2, 10, 10);
  ellipse(xplode3, yplode3, 10, 10);
  ellipse(xplode4, yplode4, 10, 10);
}

I would like to have a trail of ~60 and also have some easing for the whole thing. I have got each feature working individually but when I added in the fading.


Solution

  • Don't bite more than you can chew; learn the little things. Vectors will make your code much less messy. You can find a detailed description of the Vector class on the Processing site. In this way, instead of having two different variables xplode1 and xplode2, there will be one Vector object that stores both values. You may find those concepts difficult at first, but they'll be invaluable tools for future sketches.

    If you feel comfortable with basic concepts such as variables, functions, conditionals and loops, start studying OOP (Object Oriented Programming). Again, Daniel Shiffman comes to help.