0
votes

I am learning java game development with libgdx and have the following issue.

I have a Rectangle array which I iterate through and draw an image according to the position of the rectangle.

My Questions is how do I draw a random image every render but still keep drawing the same random image until it leaves the screen. currently it is drawing the same image but I would like know how to draw a different pipe image every iter.

Thank you

My Iterator

 Iterator<Rectangle> upperIter = upperPipes.iterator();
      while(upperIter.hasNext()) {
         Rectangle upperpipe = upperIter.next();
         upperpipe.x -= 8 * Gdx.graphics.getDeltaTime();
         if(upperpipe.x  < -32) upperIter.remove();

My draw method

public void drawPipes(){
    batch.begin();
       for(Rectangle upperPipe: Pipes.lowerPipes) {
           batch.draw(Assets.pipeImg, upperPipe.x, upperPipe.y,   upperPipe.width, upperPipe.height);
        batch.end();

       }
2

2 Answers

0
votes

One great way to get repeatable random data is to use a Random object (java.util.Random is suitable for game usage), and provide it with a non-random seed. Each time you put in the seed and request the same sequence of number types+ranges, you will get the same (psuedo-)random numbers. When you want different numbers, just change the seed.

As an example:

Random rand = new Random(1234);
System.out.println(rand.nextInt()); // an int from Integer.MIN to Integer.MAX
System.out.println(rand.nextInt(100)); // an int from 0 to 100

Will always output the following, every single time.

-1517918040
33

But change the seed (in the constructor for Random), and the output values will change. rand.setSeed(seed) will reset the Random to start its sequence over.

You could use this to produce the same set of random numbers over and over while the rect is on screen.

However, a more direct and simple way would be to to just generate one random number for each rect when it is created, and store that number until it leaves:

public void drawPipes(){

    for(int i = 0; i<Pipes.color.size; i++){
        num = Pipes.color.get(i);
    }

    for(Rectangle bottomPipe: Pipes.lowerPipes) {
        switch(num){
            case 0:
                batch.draw(Assets.redPipeImg, bottomPipe.x, bottomPipe.y, bottomPipe.width, bottomPipe.height);
                break;
            case 1:
                batch.draw(Assets.yellowPipeImg, bottomPipe.x, bottomPipe.y, bottomPipe.width, bottomPipe.height); 
                break;
        }
    }
}
0
votes

SOLVED!!

I created a custom pipe class and just created an array of pipes, each new pipe object that went into the array took a random image. I iterated through the array, and called the draw method on each pipe object.

Simple and it works perfect