Home > database >  Extra Thread decreases FPS in LibGDX Java
Extra Thread decreases FPS in LibGDX Java

Time:08-08

I am using a Thread to do some calculations related to the app that need to be done simultaneously but this Thread causes the FPS to drop (logically) and I wanted to know how to resolve the issue as the Thread is not doing any heavy calculations at all. Here is the code where I implement the Thread and the Thread itself.

        incrementMass = new IncrementMass();
        incrementMass.start();
        // I added some extra functionality to the InputProcessor but I assume that is irrelevant
        if(InputProcessor.isButtonUp() && InputProcessor.getButtonLetGo() == RIGHT && !isJustPressed) {
            isJustPressed = true;
            try {
                incrementMass.join();
            } catch(InterruptedException e) {
                e.printStackTrace();
            }
            planets.add(new Planet(10, m, mouseOnWorld2.x, mouseOnWorld2.y));
        } else if(Gdx.input.isButtonJustPressed(RIGHT)) {
            isJustPressed = false;
            incrementMass.restart();
        }

The Thread:


/**
 * Thread to increment the mass in a while loop.
 */
public class IncrementMass extends Thread {
    /**
     * Increments the mass when started.
     */
    @Override
    public void run() {
        super.run();
        while(Gdx.input.isButtonPressed(Input.Buttons.RIGHT)) {
            MainScreen.m  = 100;
            System.out.println(MainScreen.m);
        }
    }

    /**
     * Resets the mass so the whole thing starts over (for the creation of a new planet)
     */
    public void restart() {
        MainScreen.m = 100000;
    }
}

All this is called in the render() function of my Screen by the way. I have one idea as to what is causing this: Every frame I create a new Thread which is not optimal but everything else I tried failed to actually perform my calculations correctly. It definitely solves the FPS problem to have the initiation of the Thread and the ´start()´ function in the constructor of my Screen but that for some reason messes with the incrementing of the mass and makes it a fixed value: the value I reset it to in ´restart()´ I've been trying to solve this but I'm baffled so here I am.

CodePudding user response:

As said in the comment, there was no function for isButtonJustUp() which made it not be able to run sequentially. Therefore I made a Thread so that it was sequential which is not a good implementation of Threads. I've come up with a solution:

        if(Gdx.input.isButtonPressed(RIGHT)) {
            m  = 100;
        } else if(InputProcessor.isButtonJustUp() && InputProcessor.getButtonLetGo() == RIGHT) {
            planets.add(new Planet(10, m, mouseOnWorld2.x, mouseOnWorld2.y));
            m=0;
        }

I haven't made isButtonJustUp() yet but it is the best way rather than implementing an unnecessary Thread.

  • Related