How to prevent multiple objects in Java Game from slowing down the game

Viewed 94

I am creating a bullet hell game where the player tries to dodge all the bullets on screen. My current game loop updates all the objects on the screen using multiple for loops in multiple methods.

Since this is a bullet hell game, there are could be up to hundreds of bullets on screen at the same time. Also I have a method called checkCollisions that checks if the sprite of a bullet over laps a player. Due to this, the game usually starts lagging when the amount of bullets reaches over a hundred bullets because its essentially iterating over the list of bullets twice.

I thought about using running a thread on the side to update the positions of the bullets and to check the collisions. The code is shown below. Each thread essentially just calls the update methods in the main game class. However, this just made the game lag more at lower bullet numbers. I'm not sure if this is because I'm creating new thread classes or for some other reason. Or maybe it is because of all the concurrentModification errors the program is throwing.

public void actionPerformed(ActionEvent e) {
    if (inGame) {
        updateEnemies();
        projectileChecker = new Thread(new checkProjectiles(this));
        projectileChecker.start();
        //updateProjectiles();
        updateBags();
        updateCharacter();
        //checkCollisions();
        collisionChecker = new Thread(new checkCollision(this));
        collisionChecker.start();
        repaint();
    }

}

Currently I've thought of 4 ways to solve this.

  1. Continue with the thread method but (1) Use a thread executor to stop defining new threads, or (2) use a while loop inside the thread to call the method so don't have to define new threads (This seems to break the code, bullets show on screen but no longer move/disappear)
  2. Combine update projectiles and collision checker, this seems like doing twice the work for half the iterations, which doesn't seem like it will make much of a difference
  3. Stop repainting after every call of update projectile/collision check, only repaint at 60 fps or something like that.
  4. Stop drawing the background image every time it repaints. (Not that useful due to in the future would want to create a camera object that follows the player around a bigger map)

I've tried the first two and the code just doesn't work, and I have no idea how to approach the last 2. Does anyone have any suggestions?

Unrelated note, a profiler is showing the number of active threads increasing constantly through the runtime of the program. Maybe that has an effect? Also, shows that a majority of the time is taken by paintComponent.

0 Answers
Related