Reputation: 15
I'm using Processing; I have a ball that bounces when it hits the border and changes its color to random. Now I need this ball to change its color on every third bounce. Can't figure out how to do it.
Here is my current code:
float xPos;// x-position
float vx;// speed in x-direction
float yPos;// y-position
float vy;// speed in y-direction
float r;
float g;
float b;
void setup()
{
size(400, 300);
fill(255, 177, 8);
textSize(48);
// Initialise xPos to center of sketch
xPos = width / 2;
// Set speed in x-direction to -2 (moving left)
vx = -2;
yPos = height / 2;
vy = -1;
}
void draw()
{
r = random(255);
b = random(255);
g = random(255);
background(64);
yPos = yPos + vy;
// Change x-position on each redraw
xPos = xPos + vx;
ellipse(xPos, yPos, 50, 50);
if (xPos <= 0)
{
vx = 2;
fill(r, g, b);
} else if (xPos >= 400)
{
vx = -2;
fill(r, g, b);
}
if (yPos <= 0)
{
vy = 1;
fill(r, g, b);
} else if (yPos >= 300)
{
vy = -1;
fill(r, g, b);
}
}
Upvotes: 0
Views: 1106
Reputation: 25903
It is quite easy. You maintain a counter which counts the amount of bounces. Therefore you increase the counter by one after every bounce. If it reaches 3
you change the color. After that you reset the counter and repeat.
Therefore add this member variable to your class (like you already did with xPos
and others):
private int bounceCounter = 0;
which introduces the variable bounceCounter
initially holding 0
as value.
Here is the modified draw
method with highlighted changes and comments:
void draw() {
// New color to use if ball bounces
r = random(255);
b = random(255);
g = random(255);
background(64);
yPos = yPos + vy;
// Change x-position on each redraw
xPos = xPos + vx;
ellipse(xPos, yPos, 50, 50);
// Variable indicating whether the ball bounced or not
boolean bounced = false;
// Out of bounds: left
if (xPos <= 0) {
vx = 2;
bounced = true;
// Out of bounds: right
} else if (xPos >= 400) {
vx = -2;
bounced = true;
}
// Out of bounds: bottom
if (yPos <= 0) {
vy = 1;
bounced = true;
// Out of bounds: top
} else if (yPos >= 300) {
vy = -1;
bounced = true;
}
// React to bounce if bounced
if (bounced) {
// Increase bounce-counter by one
bounceCounter++;
// Third bounce occurred
if (bounceCounter == 3) {
// Change the color
fill(r, g, b);
// Reset the counter
bounceCounter = 0;
}
}
}
Upvotes: 1