Basic Array Question

Hi there!

I’ve noobie question…

I wrote a code that makes a ball appear when the key pressed minus or plus.

two questions:

  1. I want every press will make one ball (now it looks like 3 at a time).
  2. how do I make the array of negative to make a bigger ball and many balls (like 10 in one press).
Ball[] balls = new Ball[1];
float gravity = 0.1;

void setup() {
  size(800, 400);
  balls[0] = new Ball(255, 0, 0);
}

void draw() {
  background(#d75965);
  if ((keyPressed == true) && (key == '-')) {
    Ball b = new Ball(200, 100, 25); 
    balls = (Ball[]) append(balls, b);
  } else if ((keyPressed == true) && (key == '+')) {
    Ball b = new Ball(600, 100, 25); 
    balls = (Ball[]) append(balls, b);
  } else {
  }

  for (int i = 0; i < balls.length; i++ ) { 
    balls[i].gravity();
    balls[i].move();
    balls[i].display();
  }
  stroke (255);
  //    strokeWeight(4);  
  line (400, 0, 400, 400);
}

class Ball {
  float x;
  float y;
  float speed;
  float w;
  
  Ball(float tempX, float tempY, float tempW) {
    x = tempX;
    y = tempY;
    w = tempW;
    speed = 0;
  }
  
  void gravity() {
    // Add gravity to speed
    speed = speed + gravity;
  }
  
  void move() {
    // Add speed to y location
    y = y + speed;
    // If square reaches the bottom
    // Reverse speed
    if (y > height) {
      speed = speed * -0.95;
      y = height;
    }
  }
  
  void display() {
    // Display the circle
    fill(#042060);
    stroke(100);
    ellipse(x,y,w,w);
  }
}  


thank you!

Instead of using this boolean use the function with the same name (see reference, it’s with …(), so keyPressed() )

It registers only once. Good.

To add 10 times use a for loop (int i=0; i<10; i++)