I’m currently learning to make arrays of objects. Whenever I try this with objects that move across the screen, the speed of the objects increases as the number of objects in the array increases.
In the example below, I wanted 10 circles at random Y positions to move from right to left at random speeds of between 1 and 10 pixels per frame. Instead, the circles move across the screen very fast, and get even faster if I increase the number of circles.
I assume I’m putting the ‘speed’ variable in the wrong place, but I can’t figure it out.
Thanks in advance for any tips
Circle[] circles = new Circle[10];
float circleX = 880;
void setup() {
size(800,800);
for (int i = 0; i < circles.length; i++) {
circles[i] = new Circle(random(1,10), random(200,600));
}
}
void draw() {
background(255);
for (int i = 0; i < circles.length; i++) {
circles[i].drawCircle();
}
}
class Circle {
float speed;
float circleY;
Circle(float tempSpeed, float tempCircleY) {
speed = tempSpeed;
circleY = tempCircleY;
}
void drawCircle() {
fill(0);
noStroke();
ellipse(circleX,circleY,80,80);
circleX = circleX - speed;
}
}
@glv Thanks for the encouragement! Yes, I’ve been getting a bit lazy with adding comments - but clearly doing so saves a lot of time when it comes to debugging later!
@Chrisir this solves the problem. I think I understand why… Declaring the starting position as a global variable meant that every time an object changed the position, it would remain changed for the next object, and the next, and so on. (Please correct me if I’m wrong !)
In your first version, circleX was a global var, that means it was shared by all circles.
That means
all circle had the same x-position and
not individual x-positions and
that the decrease in the position ( - speed) was 10 times per frame executed (hence the circles got so fast!) and not only once (when circleX is in the class, it’s an object property, so there are 10 individual values and the speed is subtracted only once from each circleX per frame, not 10 times).
When circleX is inside the class, we achieve
individual values for each circle
speed is subtracted only once per frame (so it’s slower).