Kinetic Interfaces – Programming fundamentals – Week 2

Description:

A modification of the original ball moving animation that spawned with mouse holding, but a twist. The balls now wrap around and they get progressively faster as they wrap around the edges. I think this is a good twist on the original creation where the balls just bounced around. The template already had an ArrayList of balls for storing them so I simply used the existing architecture. As I figured out how to make the balls warp, I went to see if there was a way I could smoothly make it warp across the border, but it would see that it would require a lot more modification to the code. Including how balls are rendered when they encounter a border. Overall, I enjoyed making this animation.

// Ball.pde

// you can organize your code better by using the tabs!
// modified by Andrew Huang

class Ball {
  float x, y, size;
  color clr;
  float xspeed, yspeed;

  Ball(float tempX, float tempY) {
    x = tempX;
    y = tempY;
    size = random(10, 100);
    clr = color(random(255), random(255), random(255));

    xspeed = random(-2, 5);
    yspeed = random(-2, 5);
  }

  void display() {
    fill(clr);
    ellipse(x, y, size, size);
  }
  void move() {
    x += xspeed;
    y += yspeed;
  }
  void bounce() { // change to wrap instead
    if (x < 0) {
      //xspeed = -xspeed;
      x = width;
      xspeed -= 5;
    } else if (x > width) {
      //xspeed = -xspeed;
      x = 0;
      xspeed -= 5;
    }
    if (y < 0) {
     // yspeed = -yspeed;
      y = height;
       yspeed -= 5;
    } else if (y > height) {
      //yspeed = -yspeed;
      y = 0;
       yspeed -= 5;
    }
  }
}

// main. pde

ArrayList<Ball> balls = new ArrayList<Ball>();


void setup() {
  size(500, 600);
  noStroke();
}


void draw() {
  background(100);

  for (int i=0; i<balls.size(); i++) {
    // I suggest this way!
    // much more convenient, right?
    Ball b = balls.get(i); 
    b.move();
    b.bounce();
    b.display();
  }

  // let's add balls at the mouseX/Y position when mousePressed !
  if (mousePressed) {
    balls.add( new Ball(mouseX, mouseY) );
  }
}

Leave a Reply