Tween between random positions

Hi all,

I am trying to draw a random position and have my ellipse move/tween to a new random position on the canvas.

My code doesn't seem to be working, I think I have things in the wrong order but every attempt I make fails to achieve my desired output.

float x, y;
float x2, y2;

float damping = .03;

void setup() {
  size(500,500);
  smooth();  
  x = random(0,width);
  y = random(0,height);  
}


void draw() {
  background(255);

  x2 = random(0,width);
  y2 = random(0,height);


  x = x + (x2 - x) * damping;
  y = y + (y2 - y) * damping;

  ellipse(x,y,15,15);

  x = random(0,width);
  y = random(0,height);

}

Thanks.

Tagged:

Answers

  • The problem is that you are randomizing everything on each frame, 60 times per second! You need to draw the new position, and to keep origin and destination stable, until the goal is reached. So, you need another couple of coordinates to track the current position.

    When the goal is reached, set it to the origin and draw random numbers to get a new goal.

  • Thanks, I tried slowing everything down, which seems to also work.

    float x, y;
    float x2, y2;
    
    float damping = .09;
    
    void setup() {
      size(500, 500);
      smooth();  
      x = random(0, width);
      y = random(0, height);  
      x2 = width/2;
      y2 = height/2;
    }
    
    
    void draw() {
      //background(255);
      noStroke();
      if (frameCount%60==0) {
        x2 = random(0, width);
        y2= random(0, height);
        fill(#ffde14);
        ellipse(x2, y2, 25, 25);
      }  
    
      x = x + (x2 - x) * damping;
      y = y + (y2 - y) * damping; 
      fill(255);
      stroke(100);
      ellipse(x, y, 15, 15);
    }
    
  • An example for (linear interpolation)/(linear movement):

    float x, y, aX, aY, bX, bY;
    
    void setup() {
        size(500, 500);
        smooth();  
        aX = random(0, width);
        aY = random(0, height);  
        bX = width / 2;
        bY = height / 2;
    }
    
    
    void draw() {
        float interval = (frameCount % 60) / 60.0;
        if(interval == 0.0) {
            aX = bX;
            aY = bY;
            bX = random(0, width);
            bY = random(0, height);
            fill(#ffde14);
            noStroke();
            ellipse(bX, bY, 25, 25);
        }  
        x = lerp(aX, bX, interval);
        y = lerp(aY, bY, interval);
        fill(255);
        stroke(100);
        ellipse(x, y, 15, 15);
    }
    
Sign In or Register to comment.