We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I'm an absolute beginner with Processing. I'm attempting to create a simple window with squares that cruise around and bounce off the sides, and change colour when they collide with the sides. I've got the moving and bouncing, but for a reason I can't determine, every single square changes colour when one of them collides with the side. I assume this has something to do with the way Processing's fill() method operates. Can someone help me get the squares to change colour independently (i.e. retain their own colour when another square strikes the side)? Code below. Thank you!
//main code
int number = 100;
BallBounce[] balls = new BallBounce[number];
void setup() {
size(500,500);
frameRate(100);
for(int i = 0; i<number; i++)
{
balls[i] = new BallBounce();
}
}
void draw(){
background(255);
for(int i = 0; i<number; i++)
{
balls[i].update();
}
}
//square object
class BallBounce {
//length and height of the squares
float x = 20;
float y = 20;
//x and y locations of the squares
float xPos = random(0,width-x);
float yPos = random(0,height-x);
//direction and velocity of squares
//(negatives determine which direction)
float xDirection = random(-1,1);
float yDirection = random(-1,1);
void update() {
rect (xPos,yPos,x,y);
noStroke();
float randomColour1 = random(50,255);
float randomColour2 = random(0,255);
float randomColour3 = random(254,255);
//updating the original position by the user-defined
//distance or travel (speed)
xPos = xPos + xDirection;
yPos = yPos + yDirection;
//telling the square to reverse its x or y value
//if its edge collides with the edge of the screen
//and change colour when it does
if(xPos > width-x)
{
xDirection = -1;
fill(randomColour1, randomColour2, randomColour3);
}
if(xPos < 0)
{
xDirection = 1;
fill(randomColour1, randomColour2, randomColour3);
}
if(yPos > width-x)
{
yDirection = -.5;
fill(randomColour1, randomColour2, randomColour3);
}
if(yPos < 0)
{
yDirection = .5;
fill(randomColour1, randomColour2, randomColour3);
}
}
}
Answers
http://Studio.ProcessingTogether.com/sp/pad/export/ro.9FqnMDLUZqQCV
Thanks GoToLoop, but that doesn't help with my colour problem!
Demo below.
Kf
Thank you so much! Now could you please briefly explain what you did?
[1] I added a variable c in your BallBounce class. [2] I added a constructor to your class and initialize the color of this object. [3] When update is called, I will change this color only if there is a reversal in direction. For that, I used the new [4]
changeColor()
function and [5] I remove all the lines related to color in yourupdate()
function.Kf