Creating object arrays without the object speeding up

Hi, this is my first post :blush:

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 :folded_hands:

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;
  }
}

Welcome @Pat ,

Experiment a lot!
Save what works and copy it to a different version to experiment.
Add comments.
I add a suffix number my from 000, 001, … 999.

There are examples here:

Check out:

and the Particle Systems.

:)

You mean, something like this sketch:
https://OpenProcessing.org/sketch/1805772

I think you need to move (not copy) this line
float circleX = 880; into the class

1 Like

@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!

@GoToLoop Great example, I’m going to try recreating this. Thanks :folded_hands:

@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 :slight_smile:!)

1 Like

Hey, glad it helped!

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).

Warm regards, Chrisir