Create an object at mouse X and Y when mouse clicked

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

Tagged:

Answers

Sign In or Register to comment.