Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
ArrayList<Ball> ballList = new ArrayList<Ball>();
Ball mouseBall;
void setup()
{
  size(600, 800);
  ballList.add(new Ball(width/2, height/2, 40));
  mouseBall = new Ball(mouseX, mouseY, 20);
}
void draw()
{
  background(255);
  mouseBall.update(mouseX, mouseY);

  for (int i = 0; i<ballList.size(); i++) {
    ballList.get(i).drawBall();
    mouseBall.checkCollision(ballList.get(i)._position, ballList.get(i)._radius);
  }
    mouseBall.drawBall();
}
class Ball {
  PVector _position = new PVector();
  int _radius;
  int colour = 250;
  public Ball(int x, int y, int r) {
    _position.set(x, y, 0);
    _radius = r;
  }
  void update(int x, int y) {
    _position.set(x, y, 0);
  }

  void drawBall() {
    pushMatrix();
    fill(colour, 0, 0);
    noStroke();
    translate(_position.x, _position.y);
    ellipse(0, 0, _radius*2, _radius*2);
    popMatrix();
  }

  void checkCollision(PVector position, int radius) {
    float distance = PVector.dist(_position, position);
    if (distance <= radius +_radius) {
      println("hit");
      colour = 60;
    } else {
      colour = 255;
    }
  }
}


Exercise

Add collision detection to the last exercise in Classes and Objects.