Hi guys and gals,
This is a pretty basic question, but I am trying to make an app that has a series of "balls" that bounce around on the screen and when they approach squares on the screen, the ball will turn red.
However, I don't know how to talk to just one instance or a particular instance of a class. It seems like it should be so very easy but I am unable to figure it out. I tried this.fill() but that didn't work.
Thanks!
This is a pretty basic question, but I am trying to make an app that has a series of "balls" that bounce around on the screen and when they approach squares on the screen, the ball will turn red.
However, I don't know how to talk to just one instance or a particular instance of a class. It seems like it should be so very easy but I am unable to figure it out. I tried this.fill() but that didn't work.
Thanks!
- int nBalls = 12;
Ball balls[] = new Ball[nBalls];
int nSquares = 5;
Square squares[] = new Square[nSquares];
void setup(){
size (500, 500);
for (int i=0; i<nSquares; i++) {
squares[i] = new Square((i*100)+50,height/2);
}
for (int i=0; i<nBalls; i++) {
balls[i] = new Ball(random(0,width),random(0,height));
}
}
void draw(){
background(0);
for (int i=0; i<nSquares; i++) {
squares[i].update();
squares[i].draw();
}//end for i
for (int i=0; i<nBalls; i++) {
balls[i].update();
balls[i].draw();
for(int j=0; j<nSquares; j++) {
if(dist(balls[i].x, balls[i].y, squares[j].x,squares[j].y) < 25) {
this.fill(255,0,0);
}
}
}
}//end draw
//define Square class
class Square{
float x;
float y;
Square(float xPos, float yPos){
this.x = xPos;
this.y = yPos;
}
void draw(){
rectMode(CENTER);
rect(this.x,this.y,50,50);
}
void update(){
}
}// end square class
//define Ball class
class Ball {
float speed;
float x;
float y;
float xSpeed;
float ySpeed;
Ball(float xPos, float yPos){
this.x = xPos;
this.y = yPos;
speed = random(.15, .75);
this.xSpeed = speed;
this.ySpeed = speed;
}
void draw(){
ellipse(this.x,this.y,25,25);
}
void update() {
if(this.x < 0){
this.x = 0;
this.xSpeed *= -1;
}
if(this.x > width) {
this.x = width;
this.xSpeed *= -1;
}
if(this.y < 0){
this.y = 0;
this.ySpeed *= -1;
}
if(this.y > height) {
this.y = height;
this.ySpeed *= -1;
}
this.x +=xSpeed;
this.y +=ySpeed;
}
}
1