Search code examples
javaandroidrandomtimerlibgdx

How do i set the image to appear at the end of the timer in another random place?


Im trying to make image reappear at the end of the timer. i cant figure out what i did wrong. the image appears in a random spot in the beginning but thats it. what i need is for the application to launch and then display the 3 dots in random places and every 1 second appear in another random place

public class Main extends ApplicationAdapter {
    SpriteBatch batch;
    Texture blue;
    Texture red;
    Texture green;
    Sprite spriteb;
    Sprite spriter;
    Sprite spriteg;
    int x;
    int y;
    Random random = new Random();
    private float counter;
    private int number;

    @Override
    public void create () {
        batch = new SpriteBatch();
        blue = new Texture("blue.png");
        red = new Texture("red.png");
        green = new Texture("green.png");
        spriteb = new Sprite(blue);
        spriter = new Sprite(red);
        spriteg = new Sprite(green);
        spriteb.setPosition(random.nextInt(Gdx.graphics.getWidth()), random.nextInt(Gdx.graphics.getHeight()));
        spriter.setPosition(random.nextInt(Gdx.graphics.getWidth()), random.nextInt(Gdx.graphics.getHeight()));
        spriteg.setPosition(random.nextInt(Gdx.graphics.getWidth()), random.nextInt(Gdx.graphics.getHeight()));


    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.begin();
        spriteb.draw(batch);
        spriter.draw(batch);
        spriteg.draw(batch);
        batch.end();
    }

        public void render (float deltaTime) {
            counter -= deltaTime;
            if (counter <= 0) {
                spriteb.setPosition(random.nextInt(Gdx.graphics.getWidth()), random.nextInt(Gdx.graphics.getHeight()));
                counter += 1000; // add one second
                batch.begin();
                spriteb.draw(batch);
                batch.end();
            }
        }
}

Solution

  • Don't invent a wheel. I think this solution will be good for you:

    Timer.schedule(
        new Task(){ 
            @Override 
            public void run() {
                 spriteb.setPosition(random.nextInt(Gdx.graphics.getWidth()), random.nextInt(Gdx.graphics.getHeight()));
                 spriter.setPosition(random.nextInt(Gdx.graphics.getWidth()), random.nextInt(Gdx.graphics.getHeight()));
                 spriteg.setPosition(random.nextInt(Gdx.graphics.getWidth()), random.nextInt(Gdx.graphics.getHeight()));
            } 
        }, delay, interval);
    

    Put this code into your create() method and see if its working. Write if something still not working.