class Ball {
float x = random(0, width);
float y = 100;
float ySpeed = 1;
void move() {
y += ySpeed
}
void show() {
ellipse(x, y, 20, 20);
}
}
Ball[] balls = new Ball [1];
void setup() {
frameRate(60);
size(640, 360);
for (int i = 0; i < balls.length; i++;) {
balls[i] = new Ball();
}
}
void draw() {
background(100);
for (int i = 0; i < balls.length; i++) {
balls[i].show();
balls[i].move();
}
if (mousePressed) {
//dont know what code I can add here or if I have to do something else
}
}
something like balls=
(Balls[]) append(balls, new Ball(….));
Check reference for append
Alternatively check Arraylist
1 Like
I tried but I don’t understand.
If I use Arraylist do I have to change my entire code?
What don’t you understand
Just read the reference and type my line…
1 Like
For ArrayList you only change a few lines
Read the reference about arraylist but array will do for now
1 Like
Hi @Kenga123456,
I would advise you to use an ArrayList as it is easy to add or delete elements from it.
Please check this example to get a feel of how to use it and add new elements after a mouse click event:
ArrayList <PVector> balls;
void setup() {
size(1000, 600);
fill(230);
noStroke();
balls = new ArrayList<PVector>();
}
void draw() {
background(20);
for (int i = 0; i < balls.size(); i++) {
ellipse(balls.get(i).x, balls.get(i).y, 20, 20);
}
}
void mousePressed() {
balls.add(new PVector(mouseX, mouseY));
}
1 Like