Saturday, March 06, 2010

myBall

Ball[] myBall;
int ballAmount = 10;
int ballSize = 50;


void setup() {
  size(800,600);
  background(255);
  smooth();
  
  //class setup
  myBall = new Ball[ballAmount];
  for (int i = 0; i < ballAmount; i++) {
    float x = random(ballSize/2,width-ballSize/2);
    float y = random(ballSize/2,height-ballSize/2);
    myBall[i] = new Ball(x ,y);
  }
}


void draw() {
  background(255);
  for (int i = 0; i < ballAmount; i++) {
    myBall[i].step();
    for(int j = 0; j < i; j++) {
      float distance = dist(myBall[i].x, myBall[i].y, myBall[j].x, myBall[j].y);
      if (distance < ballSize) {
        float incXHolder = myBall[i].incX;
        float incYHolder = myBall[i].incY;
        myBall[i].collisionHandler(myBall[j].incX, myBall[j].incY);
        myBall[j].collisionHandler(incXHolder, incYHolder);
      }
      if (distance < ballSize-5) {
        myBall[i].randPos();
        myBall[j].randPos();
      }
    }
    myBall[i].drawBall();
  }
}


class Ball {
  float x;
  float y;
  float incX;
  float incY;
  
  int c;

  //constructor
  Ball(float _x, float _y) {
    x = _x;
    y = _y;
    setInc();
    c = 0;
  }
  
  //speed
  void setInc() {
    incX = random(-2, 2);
    incY = random(-2, 2);
  }
  
  //reset
  void randPos() {
    x = random(ballSize/2,width-ballSize/2);
    y = random(ballSize/2,height-ballSize/2);
    c = 255;
  }
  
  //the ball
  void drawBall() {
    noStroke();
    fill(c);
    ellipse(x, y, ballSize, ballSize);
  }
  
  //direction
  void step() {
    if (x > width-ballSize/2 || x < ballSize/2) {
      incX = -incX;
    }
    if (y > height-ballSize/2 || y < ballSize/2) {
      incY = -incY;
    }
    x = x + incX;
    y = y + incY;
  }
  
  //collision
  void collisionHandler(float _incX, float _incY) {
    incX = _incX;
    incY = _incY;
    c = 0;
  }
}

info info

submitted by: kim
views: 620
just some balls in a box

Tags: ball, distance, collision

comments comment

loading loading...

 

Add a comment: