We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi there
i have a question which is how to add a counter for the balls that hit the rectangle ?
this is the code
float x, y, speedX, speedY;
float diam = 10;
float rectSize = 100;
final int WIDTH = 1366;
final int HEIGHT = 768;
final int NUM_OF_BALLS = 64;
final int BALL_SIZE = 25;
float ball_x[] = new float[NUM_OF_BALLS];
float ball_y[] = new float[NUM_OF_BALLS];
float ball_dx[] = new float[NUM_OF_BALLS];
float ball_dy[] = new float[NUM_OF_BALLS];
void setup() {
fullScreen( );
fill(0, 255, 0);
reset();
for (int i = 0; i < NUM_OF_BALLS; i ++) {
ball_x[i] = random(0, rectSize);
ball_y[i] = random(0, rectSize);
ball_dx[i] = random(-3, 3);
ball_dy[i] = random(-3, 3);
}
}
void reset() {
x = width/2;
y = height/2;
speedX = random(3, 5);
speedY = random(3, 5);
}
void draw() {
background(0);
for (int i = 0; i < NUM_OF_BALLS; i ++) {
ellipse(ball_x[i], ball_y[i], BALL_SIZE, BALL_SIZE);
ball_x[i] += ball_dx[i];
ball_y[i] += ball_dy[i];
if (ball_x[i] >= WIDTH - BALL_SIZE) ball_dx[i] = -ball_dx[i];
if (ball_y[i] >= HEIGHT - BALL_SIZE) ball_dy[i] = -ball_dy[i];
if (ball_x[i] <= BALL_SIZE) ball_dx[i] = -ball_dx[i];
if (ball_y[i] <= BALL_SIZE) ball_dy[i] = -ball_dy[i];
rect(0, 0, 0, height);
rect(width-15, mouseY-rectSize/2, 10, rectSize);
x += speedX;
y += speedY;
// if ball hits movable bar, invert X direction
if ( x > width-15 && x < width -20 && y > mouseY-rectSize/2 && y < mouseY+rectSize/2 ) {
speedX = speedX * -1;
}
// if ball hits wall, change direction of X
if (x < 25) {
speedX *= -1.1;
speedY *= 1.1;
x += speedX;
}
// if ball hits up or down, change direction of Y
if ( y > height || y < 0 ) {
speedY *= -1;
}
}
}
void mousePressed() {
reset();
}
Answers
How did you solve it?
Since I have a nice, large monitor, this small change is immediately more fun (and a lot less of a tease):
yes, don't define WIDTH and HEIGHT, they are already available as width and height and will reflect the screen size if you use fullscreen().
you could increment a counter in the block here. use a global variable.
Thank you
Hello , how to connect the slider with the acceleration of the balls ?