Reputation: 3
I am making a program that draws a pattern/design using balls that bounce around the screen using Processing. I have managed to get one ball, moving, drawing, and bouncing properly. However, once I made my ArrayList, and drawn all my balls on the screen using an Iterator, they stopped moving.
I'm not really sure what to do, I've tried calling move() in the iterators while loop, and tried calling it in the constructor of Ball() (don't really know if that does anything). I only included the code that I think I was having problems with.
import java.util.ArrayList;
import java.util.Iterator;
class Ball {
float x;
float y;
float directionDegree;
float speed = 8;
Ball() {
x = random(0, 600);
y = random(0, 600);
directionDegree = random(60, 120);
}
void move() {
x += speed * Math.cos(direction);
y += speed * Math.sin(direction);
}
void drawAll(ArrayList<Ball> balls) {
Iterator<Ball> iter = balls.iterator();
while (iter.hasNext()) {
iter.next().draw();
move();
}
}
}
Inside Main Class:
Ball b;
ArrayList<Ball> balls = new ArrayList<Ball>();
int amountOfBalls;
void setup() {
size(600, 600);
b = new Ball();
amountOfBalls = 4;
for (int i = 0; i < amountOfBalls; i++) {
balls.add(new Ball());
}
}
void draw() {
b.drawAll(balls);
b.contactWall();
b.move();
}
The four balls I drew just sit there, don't move and don't make any wacky movements, they just sit there.
Upvotes: 0
Views: 130
Reputation: 952
As suggested by BarSahar, there is no reference of Ball in the move function call. You can also do the below code in while loop
Ball ball = iter.next();
ball.draw();
ball.move();
But I would recommend you to move the draw All method from the Ball class and put it inside the main class. You can directly call draw All from main Class. inside draw All you can iterate using foreach loop and can call draw, move and connect`Wall.
Upvotes: 1
Reputation: 69
Notice that I'm your "while" loop, you only use the iterator for drawing. When calling the method "move", the function doesn't have a reference for the particular ball you want to move.
I'd suggest something along the lines of:
For (Ball ball : balls) {
ball.move();
ball.draw();
}
By the way the draw function in the main class uses the move method unnecessarily (since the ball already does that in "move").
And also I'd suggest making the "drawAll()" function a static one. Since it doesn't operate on a single instance of ball "b", just as a good practice
Upvotes: 0