Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a random number in LibGDX

Tags:

android

libgdx

I don't know why but I cant seem to see how random number generation works in LibGDX, no good examples of it being used that I can find either. Just wondering how you can just random a number 1-3 then System.out it. Bonus - How can you random a new number every second?

like image 675
CodingNub Avatar asked Dec 02 '22 20:12

CodingNub


2 Answers

You can use standard Java to do that.

Random random = new Random();
int oneTwoThree = random.nextInt(3) + 1;

This will generate a random int (0, 1 or 2) and then add 1, resulting in 1, 2 or 3.

If you want to switch it every second, then you need to keep track of the time in your render(float) method

private float countDown;

private int randomNumber;

public void render(float deltaTime) {
    countDown -= deltaTime;
    if (countDown <= 0) {
        Random random = new Random();
        randomNumber= random.nextInt(3) + 1;
        countDown += 1000; // add one second
    }
}
like image 172
noone Avatar answered Dec 21 '22 09:12

noone


import com.badlogic.gdx.math.MathUtils;


int random = MathUtils.random.nextInt(4);

        if(random == 0){

        }else if (random == 1){

        }else if (random == 2){

        }else{

        }
like image 38
Jason Hintlian Avatar answered Dec 21 '22 08:12

Jason Hintlian