Search code examples
c++while-looppong

While loop out of control Pong game


So my problem is this: I am making a pong game and the velocity of the ball is calculated using the screen size and on my PC it works fine. When i send the game to a friend the ball seems to move extremely fast. I think the problem is in the while loop because i put a counter in it to delay the start of the game. However on other PCs it seems like the while loop is spinning so fast it disregards the counter all together and starts the game instantaneously. My PC isn't low-end by any means so i cannot figure out what the problem is.


Solution

  • This is well-known and well-solved problem. Simple games from the 80's suffer from this problem. They were built to redraw the screen as fast as your computer would allow, and now (assuming you can get them to run) they run unplayably fast. The speed at which your game runs should not be determined by how fast your computer can execute a while loop, or your game will never play the same on two computers.

    Games have solved this problem for decades now by scaling the advancement of the game-state by the frame-rate of the computer currently running the game.

    The first thing you need to do in your while loop is calculate the elapsed time since the last iteration of your loop, this will be some tiny fraction of a second. Your game state needs to advance by that much time, and only that much time.

    In very simple terms, if you're moving your ball using something like this...

    ball_x += ball_horizontal_momentum
    ball_y += ball_vertical_momentum
    

    You would need to modify each momentum by a scaling factor determined by how much time has passed:

    ball_x += ball_horizontal_momentum * elapsed_time
    ball_x += ball_vertial_momentum * elapsed_time
    

    So, on a very slow computer your ball might wind up jumping 100 pixels each frame. On a computer which is 10 times faster, your ball would move 10 pixels each frame. The result is that on both computers, the ball will appear to move the exact same speed.

    All of your animations need to be scaled in this way.