Search code examples
javalibgdxgeometry

Libgdx falling circles


I am working on a libgdx game and am having a certain problem. I am trying to constantly generate random coordinates (above the screen) and for each coordinate, draw a circle. Then add to their y-coordinates so they will have a falling effect. Once a circle is off the screen, it will be deleted.

Here I create 2D list. It contains arrays of random coordinates in the screen.

List<List<Integer>> lst = new ArrayList<List<Integer>>();

public void makePoints() {
    Random generator = new Random();
    for (int i = 0; i < 10; i++) {
        List<Integer> lst1 = new ArrayList<Integer>();
        int randX = randInt(10,Gdx.graphics.getWidth()-10);
        int randY = randInt(Gdx.graphics.getHeight()/5,Gdx.graphics.getHeight()-10);
        lst1.add(randX);
        lst1.add(randY);
        lst.add(lst1);
    }
}

Once prior to the game loop, I call the function

Then inside the game loop, I do this. (Keep in mind this is run over and over)

//Draw a circle for each coordinate in the arraylist
    for (int i=0; i<lst.size();i++){
        shapeRenderer.circle((lst.get(i)).get(0), (lst.get(i)).get(1), 30);
    }

    //Add 1 to the y value of each coordinate
    for (int i=0; i<lst.size();i++){
        lst.get(i).set(1, i + 1);
    }

Currently, it draws 10 circles and drops them extremely fast. I need to be able to constantly generate points and slow down the dropping.

Thank you very much!


Solution

  • You should consider using a while loop, which runs while the game is still alive. Remove your for i less than 10 loop and implement the while loop and it will continue to create balls for lifetime of the thread. As for slowing down the creation of the balls - call the thread.sleep() function and implement a similar method to this:

    public void run()
    {
            while (alive)
            {
                createNewCircle();
                updateGame();
                repaint();
                try
                {
                    Thread.sleep(100);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
    }
    

    For more information on programming with threads - Check this out