Search code examples
libgdx

How to make a drawn shape stay on the screen? LIBGDX


Currently I have a float value set to draw a rectangle to the screen once the delta time reaches 4, and once the value reaches four the rectangle will stay on the screen for a split second and then disappear. How do I make it so that it will stay on the screen, because I'd like to have a new rectangle appear every 4 seconds?


Solution

  • So you want to make rectangles after every four seconds and you want them to stay on the screen. I guess what you might be doing is repositioning the same rectangle everytime and that is why you see the rectangle disappear.

    Anyways, here is how you do this:

    Draw a function that will keep creating rectangles for you

    private void spawnRectangle() {
        Rectangle myRectangle = new Rectangle();
        myRectangle .x = MathUtils.random(0, Gdx.graphics.getWidth()-400);
        myRectangle .y = Gdx.graphics.getHeight();
        myRectangle .setSize(400,40);
        myList.add(myRectangle); //you need this list to store all the rectangles
    }
    

    So in the above code, i am making rectangles randomly in the x-axis and topmost at the y-axis.

    Now call this function every 4 sec

    timeTracker+=Gdx.graphics.getDeltaTime();
    if(timeTracker>=4){
      timeTracker=0;
    }
    

    Now draw the sprites to the position of these rectangles

        for(Rectangle myRectangle: myList) {
            batch.draw(mySprite, myRectangle.x, myRectangle.y,myRectangle.width,myRectangle.height);
        }