We are about to switch to a new forum software. Until then we have removed the registration on this forum.
So, I'm new to processing and coding in general, I've learned how to program the famous bouncing ball and I could also program a ball class and create and array of balls. My program now creates a ball in the X and Y mouse when I click, but everytime I click, every ball in the canvas resets its position to the x and y pos... this is so dumb and I don't know how to fix it. Below is my code:
Ball[] balls = new Ball[100];
int adding = 0;
void setup() { size(640, 360); } void mousePressed() { adding += 1; for ( int i = 0; i < balls.length; i++) { balls[i] = new Ball(mouseX, mouseY, random(5, 30)); } }
void draw() { background(255);
for (int i = 0; i < adding; i++) { balls[i].show(); balls[i].update(); balls[i].edges(); } }
class Ball {
float r = random(5,30); float x = random(30,600); float y = random(30,300); float ySpeed = random(-6, 6); float xSpeed = random(-6, 6);
Ball (float tempX, float tempY, float tempR) { x = tempX; y = tempY; r = tempR; } void show() { fill(0); strokeWeight(2); ellipse(x, y, r2, r2);
}
void update() { y += ySpeed; x += xSpeed; }
void edges() {
if (x > width || x < 0) {
xSpeed *= -1;
}
if (y > height-r || y < 0) {
ySpeed *= -1;
}
} }
I'm new to this, as you can see. haha
Answers
No for loop in mousePressed just
Thanks! I wrote this, is it ok or there's a better way? it worked by the way
void mousePressed() { balls[adding] = new Ball(mouseX,mouseY); adding += 1;
}
Much better now
https://Forum.Processing.org/two/discussion/15473/how-to-format-code-and-text
When using adding++ you can maximum go to 100 - you can test this with if(adding<100)...
When using an ArrayList instead of array you can just use add() to add many balls
Also when balls expire you can remove() them from the ArrayList