2

I built a small game in java in which i use a game loop. I add gameobjects which i render using render() and tick() methods. However, now the program gets bigger i encounterted a problem. How do you solve that when i use velocity to move a picture, the object keeps rendering on old positions? For small programs this aint a problem, but when you get like 100 objects in the screen the FPS keeps dropping to the point the program doesnt work properly anymore. This is just because there are so many objects to render. Is there a way to remove the rendering of the old positions of the object? Here below is some code i have written.

The game loop i used:

public void run() {
    this.requestFocus();
    long lastTime = System.nanoTime();
    double amountOfTicks = 60.0;
    double ns = 1000000000 / amountOfTicks;
    double delta = 0;
    long timer = System.currentTimeMillis();
    int frames = 0;
    while (running) {
        long now = System.nanoTime();
        delta += (now - lastTime) / ns;
        lastTime = now;
        while (delta >= 1) {
            tick();
            delta--;
        }
        if (running) {
            try {
                render();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (FontFormatException e) {
                e.printStackTrace();
            }
        }
        frames++;

        if (System.currentTimeMillis() - timer > 1000) {
            timer += 1000;
            System.out.println("FPS: " + frames);
            frames = 0;
        }
    }
    stop();
}

I used the Graphics class in Java to draw the images/strings/rectangles/etc. on the JFrame.

Here below is a picture of the problem. You can see that the object began all the way to the right. I changed the x-axis every tick of the game loop which made the object go to the left. Unfortunately, the object leaves a trace behind it and keeps rendering that, while i want it to only render the newest position.

Object rendering problem picture:

https://i.stack.imgur.com/iUPH2.png

How can i solve this? Thanks in advance.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • 1
    *Is there a way to remove the rendering of the old positions of the object?* - you need to clear the background of your painting area. You don't show your painting code so we cant' suggest exactly what you need to do. Check out: https://stackoverflow.com/questions/54028090/get-width-and-height-of-jpanel-outside-of-the-class/54028681#54028681. Change the number of balls from 5 to 100 to see if it does what you want. – camickr Jan 05 '22 at 15:35
  • 1
    Ayy thanks @camickr. After a few hours i finally got it, my program was already quite big which made it a lot harder. I looked at the link you highlighted and used the override paintComponent which (after changing my whole code completely) worked haha. – Jill Jessurun Jan 05 '22 at 17:48

0 Answers0