We are about to switch to a new forum software. Until then we have removed the registration on this forum.
In the programme below I tried to make it so when ever you clicked the screen it creates a ball that bounces around. But when I click the screen a black circle appears and does nothing, can someone help me fix my code?
ArrayList<Ball> balls;
void setup() {
size (640, 360);
balls = new ArrayList<Ball>();
for (Ball ball : balls){
ball.Setup();
}
}
void draw() {
background (55);
for (Ball ball : balls){
ball.show();
ball.update();
}
}
void mousePressed() {
balls.add(new Ball(mouseX, mouseY));
}
class Ball {
float a;
float b;
float movex;
float ballx;
float movey;
float bally;
int fcolor;
public Ball(float ballx, float bally) {
this.ballx = ballx;
this.bally = bally;
}
void Setup() {
fcolor = 255;
ballx = width/2;
bally = height/2;
a = random(-6, 6);
b = random(6, -6);
if ( a < 0) {
movex = -6;
} else {
movex = 6;
}
if (b < 0) {
movey = -6;
} else {
movey = 6;
}
}
void show() {
fill (fcolor);
stroke (fcolor);
ellipse (ballx, bally, 50, 50);
}
void update() {
ballx = ballx + movex;
bally = bally + movey;
if (ballx > width) {
ballx = width;
movex = -movex;
fcolor = color(random(255), random(2, 55), random(0, 255));
}
if (ballx < 0) {
ballx = 0;
movex = -movex;
fcolor = color(random(0, 255), random(0, 255), random(0, 255));
bally = bally + 0.2;
}
if (bally > height) {
bally = height;
movey = -movey;
fcolor = color(random(0, 255), random(0, 55), random(0, 255));
}
if (bally < 0) {
bally = 0;
movey = -movey;
fcolor = color(random(0, 255), random(0, 255), random(0, 255));
}
}
}
Answers
You don't need line 7 and 8. Your array list is empty at this point. The second change you need to do is to call Setup() function (from your Ball class) inside your constructor in line 47.
Kf
http://studio.ProcessingTogether.com/sp/pad/export/ro.9oyKfI9kOIa77/latest