0

I have a while loop that runs the logic of a simple 2d game I am developing. Inside it I have a lot of function calls that seem to be varying in speed which makes the ball in the game stutter a lot. I wanted to try to make each loop last the same amount of time to eliminate the stutter.

I have tried to limit the amount of function calls which didn't work because even with the fewest amount it still did stutter. I have also tried using pause() to save time but that just made it go slower.

 private void turn() {
        Ball ball = new Ball(400, 500);
        add(ball);

        pause(3000);

        while(ball.getCenterY() + ball.getRadius() <= CANVAS_HEIGHT){

            ball.updatePosition(1);

            wallPaddleCollision(ball);

            brickCollision(ball);

            if (numberOfBricks == 0) {
                System.out.println("You've Won!");
            }

            pause(1);
        }

        lives--;

        if(lives > 0) {
            remove(ball);
            turn();
        }
        else {
            loss();
        }
    }
...
More code in here.
...
}

It should be running smoother than this. Any advice?

aaaaaaaaaron_g
  • 73
  • 1
  • 2
  • 10
  • 1
    Hey! You'll want to look into how "game loops" work and the different types of game loops. By looking into past questions on Java game loops, you should be able to structure a proper tick/render loop. – devshawn Apr 09 '19 at 03:52

1 Answers1

1

There are multiple aspects here:

  • ideally, your "worker" methods are written in a way that they do not do 5 things in one loop iteration and then 5000 in the next. They should be relatively "constant".
  • you can't speed up things. If at all, you can get System.currentTimeMillis() in the beginning of each loop, and in the end. You could then determine "this loop was a bit too fast, so artificially do nothing for 50 milliseconds".
GhostCat
  • 137,827
  • 25
  • 176
  • 248