Why can't I get the ellipse to bounce back - in recursive code?

edited December 2015 in Questions about Code

This example is based off the simple bouncing ball example, but cannot seem to replicate that example if attempting to use a recursive function in draw().

When I try to debug showing the value of my controller variable, I see that I am getting a +/- value. Where am I going wrong?

If I can get an explanation or where to look that would be best as I am trying to learn. - Thank You



//float speed = .05;
float speed;
float x;

void setup() {
  size(500,500);
  background(150);
  smooth();
  ellipseMode(CENTER);
  noFill();
  strokeWeight(2);
  stroke(255);
}

void draw() {
  background(0);
  moveIn(width/2, height/2, 400);
  //speed += .05; // this could be issue!
  x += speed;
  println(speed); // speed showing -speed -- check if getting flipped
}

void moveIn(float x, float y, float s) {
// speed = speed +.05;
   if (x >= width) {
     println("Hit Width");
     speed *=-1;  // this is one issue!
  }
  ellipse(x,y,s,s);
   if(s > 0) {
    x = x + speed;
    speed += .005; // this could be issue!
    s = s - 20;
    moveIn(x + speed, y, s);
   }
}
Tagged:

Answers

  • Answer ✓

    I think you have strangely named variables, speed doesn't really fit here, because the ellipses don't really move, the first is always drawn at the same position, the others are displaced. So i would rename 'speed' to 'offset'. When you hit the right border, you invert the "speed" and the displacement will be negative, resulting in all circles getting displaced to the left.

    Here is an example, with renamed variables. It does now invert the variable "increment" instead of the offset.

    float offset, x;
    float increment = .005;
    
    void setup() {
      size(500, 500);
      ellipseMode(CENTER);
      noFill();
      strokeWeight(2);
      stroke(255);
    }
    
    void draw() {
      background(0);
      moveIn(width/2, height/2, 400);
    }
    
    void moveIn(float x, float y, float s) {
      if (x >= width || x <= 0) {
        increment *=-1;
      }
      ellipse(x, y, s, s);
    
      if (s > 0) {
        offset += increment; 
        x = x + offset;
        s = s - 20;
        moveIn(x + offset, y, s);
      }
    }
    
Sign In or Register to comment.