Random Speed in an array + looping objects in the Y axis

Hello, I am currently trying to make a game where objects float past the user constantly (current max objects on screen is 10).

I am using an array for these 'class Rocks' objects.

I however can't seem to make the objects in the array move at different speeds from each other, it appears to apply to the batch as a whole.

Also I can't figure out how to get the objects to loop back to the bottom and re-randomize their x-axis location + size upon reaching the top.

(I only have my toploop function and not the size and x-axis one as if I'm not wrong, it's based on the same idea and once I figure out toploop the rest should follow)

Here's my tab for the main sketch and subsequently the class Rocks tab

Rock[] rocks = new Rock[10];


void setup() {
  size(500, 700);
  for (int i = 0; i<10; i++) {
    rocks[i] = new Rock();
  }
}
void draw() {
  background(30);
  for (int i = 0; i<10; i++) {
    rocks[i].appearance();
    rocks[i].rise();  }
}

class Rock {

  float x;
  float y;
  float rSize;
  float yspeed;

  Rock() {

    x = random(width);
    y = random(750, 1000);
    rSize = random(10, 50);
    yspeed = random(-1,-5);
  }

  void appearance() {
    fill(250);
    ellipse (x, y, rSize, rSize);
  }

  void rise() {
    y += yspeed;
  }

 /* void toploop() {

    if (y <= 0); 
    y = random(750, 1000); 
    println(y);
  } */
}

I commented out the toploop function because it just kept assigning them a random value of y

I feel like i'm missing something really rudimentary but I'm also quite new to coding in general

Please and thank you in advance!

Tagged:

Answers

  • The random() function can take two arguments, a lower bound and an upper bound. They have to be in the correct order for it to work.

    Look at how you're calling it:

    yspeed = random(-1,-5);
    

    The problem is that -1 is greater than -5, so you've got them reversed. If you switch their order, your program works fine.

    As for your other error, take a look at your if statement:

    if (y <= 0); 
        y = random(750, 1000); 
        println(y);
    

    Notice the ; at the end of the if statement. This basically says "if y <= 0, do nothing. Then every time, assign a random value to y."

    To fix this, you need to wrap your if statement in curly brackets:

    if (y <= 0){
        y = random(750, 1000); 
        println(y);
    }
    

    In fact you should always wrap your if statement in curly brackets, that way you avoid this problem altogether.

  • Thanks very much, everything is now in working order!

Sign In or Register to comment.