Search code examples
javaandroidlibgdx

2D game, random created object


Ive been working on a game in libgdx for a while..my project includes a space ship and some meteors.

here is the class i made

public class asteroid {
public static final int var=1080-150;
private Sprite sprite_asteroid;
private int posAsteroidx,posAsteroidy;
Rectangle asteroidBounds=new Rectangle();
private Random rand;

public asteroid(){
    sprite_asteroid=new Sprite(new Texture(Gdx.files.internal("asteroid.png")));
    rand = new Random();
    posAsteroidx=rand.nextInt(var);
    posAsteroidy=1920+rand.nextInt(1920);
    asteroidBounds.set(posAsteroidx,posAsteroidy,150,150);
}
public void reposition(){
    posAsteroidy-=10;
}

In the gamescreen i've created one array private Array<asteroid> asteroids; and added some for (int i=1;i<=asteroidCount;i++) asteroids.add(new asteroid());

Somewhere in gamescreen i check for collisions with the ship

        for (asteroid asteroid : asteroids) {
        if (asteroid.asteroidBounds.overlaps(shipbounds))
        {
            asteroid.setPosAsteroidx(rand.nextInt(1080-150));
            asteroid.setPosAsteroidy(1920 + rand.nextInt(1920));
            shipLives--;
            break;
        }

    }

So, collisions working fine but the problem is that sometimes(ok, maybe a lot of times) my meteors are overlapsing...what should i do so there won't be any meteors on top of others?


Solution

  • The best way to prevent overlap would be similar to how you check the ship collisions. You would need to loop through the asteroids and compare it to the other asteroids to see if they are overlapping.

    Try something like this:

    for (int i = 0; i < asteroids.size() - 1; i++) {
        for (int j = i + 1; j < asteroids.size(); j++) {
            if (asteroids[i].asteroidBounds.overlaps(asteroids[j].asteroidBounds))
                //Insert collision handling code here
        }
    }
    

    You'll have to modify the if statement a bit. I'm not sure if I'm using your overlaps function or astroidBounds correctly. Hope that helps!