Eldar Bakerman
Eldar Bakerman

Reputation: 3

Randomizing Coordinates through Arrays

I have been trying to make a button teleport to a random place on screen (in one of the 9 given coordinates) when the button is clicked, that worked fine but then I have seen that a common result is that the button stays in place, I have then created a new array that does not include the current coordinates of the button, that worked in the aspect of the button not staying in the same place, however, now I experience a new issue, for some unknwon reason - yes, I tried to debug - there are only 2 coordinates the button goes to, here is the code:

    gameBtnRX = gameBtn.getX(); //Getting the current X of the button
    gameBtnRY = gameBtn.getY(); //Getting the current Y of the button


    switch ((int) gameBtnRX) { //Setting the _randArgsX array values
        case 200: _randArgsX = new float[]{600, 1000}; break;
        case 600: _randArgsX = new float[]{200, 1000}; break;
        case 1000: _randArgsX = new float[]{200, 600}; break;
        default: _randArgsX = new float[]{200, 600, 1000}; break;
    }

    switch ((int) gameBtnRY) { //Setting the _randArgsY array values
        case 500: _randArgsY = new float[]{1000, 1500}; break;
        case 1000: _randArgsY = new float[]{500, 1500}; break;
        case 1500: _randArgsY = new float[]{500, 1000}; break;
        default: _randArgsY = new float[]{500, 1000, 1500}; break;
    }

    randGameBtnX = rand.nextInt(_randArgsX.length - 1); //Randomizing one of (max 3) the values in the array
    randGameBtnY = rand.nextInt(_randArgsY.length - 1); //And putting them as the X and Y of gameBtn
    gameBtnX = _randArgsX[randGameBtnX];
    gameBtnY = _randArgsY[randGameBtnY];
    gameBtn.setX(gameBtnX);
    gameBtn.setY(gameBtnY);

(The 200,600,100 are the possible X coordinates, and the 500,1000,15000 are the possible Y coordinates)

Upvotes: 0

Views: 52

Answers (1)

Dabiuteef
Dabiuteef

Reputation: 475

See Random.nextInt(int)

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive).

Therefore there is no need to minus one to the length of arrays.

Upvotes: 1

Related Questions