1

I'm quite new to programming and was just wondering the best or a quick way to spawn an object avoiding overlap in a java game.

I have an array of spike pits that I want to place randomly on the level. The code I currently have for painting the image on screen is:

    // Initialise all Spike Pits
    for (int k = 0; k < NUMBER_OF_SPIKEPITS; k++) {
        spikepitX = rand.nextInt(3600) + (thePlayer.getX() + 20); //will ensure that the spike pit cannot spawn under the player start position
        spikepitY = (GroundLevel - 33);

        spikepit[k] = new SpikePit(spikepitX, spikepitY);
    }

    init();

This prints them at random points along the ground for the width of the level, but some of them overlap. Is there anything I can add to prevent this?

Jeff Grant
  • 11
  • 2
  • Does [this](http://stackoverflow.com/questions/16000196/java-generating-non-repeating-random-numbers) help? – jrook Apr 20 '17 at 22:43
  • If you plan to rely on pseudo-random number generation, only take into account the coordinate range where the player is not located. Otherwise, you'll have to continuously generate a coordinate and check if it's valid. – Jacob G. Apr 20 '17 at 22:54

1 Answers1

-1

You can add spikepitX to a list, then check if your new spikepitX is available in this this or not, if yes then get another spikepitX then go check again.

TuyenNTA
  • 1,194
  • 1
  • 11
  • 19