Home > Articles

This chapter is from the book

Updating the Game

Most video games have some concept of time progression. For real-time games, you measure this progression of time in fractions of a second. For example, a game running at 30 FPS has roughly 33 milliseconds (ms) elapse from frame to frame. Remember that even though a game appears to feature continuous movement, it is merely an illusion. The game loop actually runs several times per second, and every iteration of the game loop updates the game in a discrete time step. So, in the 30 FPS example, each iteration of the game loop should simulate 33ms of time progression in the game. This section looks at how to consider this discrete progression of time when programming a game.

Real Time and Game Time

It is important to distinguish real time, the time elapsing in the real world, from game time, the time elapsing in the game’s world. Although there often is a 1:1 correspondence between real time and game time, this isn’t always the case. Take, for instance, a game in a paused state. Although a great deal of time might elapse in the real world, the game doesn’t advance at all. It’s not until the player unpauses the game that the game time resumes updating.

There are many other instances where real time and game time might diverge. For example, some games feature a “bullet time” gameplay mechanic that reduces the speed of the game. In this case, the game time must update at a substantially slower rate than actual time. On the opposite end of the spectrum, many sports games feature sped-up time. In a football game, rather than requiring a player to sit through 15 full minutes per quarter, the game may update the clock twice as fast, so each quarter takes only 7.5 minutes. And some games may even have time advance in reverse. For example, Prince of Persia: The Sands of Time featured a unique mechanic where the player could rewind the game time to a certain point.

With all these ways real time and game time might diverge, it’s clear that the “update game” phase of the game loop should account for elapsed game time.

Logic as a Function of Delta Time

Early game programmers assumed a specific processor speed and, therefore, a specific frame rate. The programmer might write the code assuming an 8 MHz processor, and if it worked properly for those processors, the code was just fine. When assuming a fixed frame rate, code that updates the position of an enemy might look something like this:

// Update x position by 5 pixels
enemy.mPosition.x += 5;

If this code moves the enemy at the desired speed on an 8 MHz processor, what happens on a 16 MHz processor? Well, because the game loop now runs twice as fast, the enemy will now also move twice as fast. This could be the difference between a game that’s challenging for players and one that’s impossible. Imagine running this game on a modern processor that is thousands of times faster. The game would be over in a heartbeat!

To solve this issue, games use delta time: the amount of elapsed game time since the last frame. To convert the preceding code to using delta time, instead of thinking of movement as pixels per frame, you should think of it as pixels per second. So, if the ideal movement speed is 150 pixels per second, the following code is much more flexible:

// Update x position by 150 pixels/second
enemy.mPosition.x += 150 * deltaTime;

Now the code will work well regardless of the frame rate. At 30 FPS, the delta time is ~0.033, so the enemy will move 5 pixels per frame, for a total of 150 pixels per second. At 60 FPS, the enemy will move only 2.5 pixels per frame but will still move a total of 150 pixels per second. The movement certainly will be smoother in the 60 FPS case, but the overall per-second speed remains the same.

Because this works across many frame rates, as a rule of thumb, everything in the game world should update as a function of delta time.

To help calculate delta time, SDL provides an SDL_GetTicks member function that returns the number of milliseconds elapsed since the SDL_Init function call. By saving the result of SDL_GetTicks from the previous frame in a member variable, you can use the current value to calculate delta time.

First, you declare an mTicksCount member variable (initializing it to zero in the constructor):

Uint32 mTicksCount;

Using SDL_GetTicks, you can then create a first implementation of Game::UpdateGame:

void Game::UpdateGame()
{
   // Delta time is the difference in ticks from last frame
   // (converted to seconds)
   float deltaTime = (SDL_GetTicks() - mTicksCount) / 1000.0f;
   // Update tick counts (for next frame)
   mTicksCount = SDL_GetTicks();
   
   // TODO: Update objects in game world as function of delta time!
   // ...
}

Consider what happens the very first time you call UpdateGame. Because mTicksCount starts at zero, you end up with some positive value of SDL_GetTicks (the milliseconds since initialization) and divide it by 1000.0f to get a delta time in seconds. Next, you save the current value of SDL_GetTicks in mTicksCount. On the next frame, the deltaTime line calculates a new delta time based on the old value of mTicksCount and the new value. Thus, on every frame, you compute a delta time based on the ticks elapsed since the previous frame.

Although it may seem like a great idea to allow the game simulation to run at whatever frame rate the system allows, in practice there can be several issues with this. Most notably, any game that relies on physics (such as a platformer with jumping) will have differences in behavior based on the frame rate.

Though there are more complex solutions to this problem, the simplest solution is to implement frame limiting, which forces the game loop to wait until a target delta time has elapsed. For example, suppose that the target frame rate is 60 FPS. If a frame completes after only 15ms, frame limiting says to wait an additional ~1.6ms to meet the 16.6ms target time.

Conveniently, SDL also provides a method for frame limiting. For example, to ensure that at least 16ms elapses between frames, you can add the following code to the start of UpdateGame:

while (!SDL_TICKS_PASSED(SDL_GetTicks(), mTicksCount + 16))
   ;

You also must watch out for a delta time that’s too high. Most notably, this happens when stepping through game code in the debugger. For example, if you pause at a breakpoint in the debugger for five seconds, you’ll end up with a huge delta time, and everything will jump far forward in the simulation. To fix this problem, you can clamp the delta time to a maximum value (such as 0.05f). This way, the game simulation will never jump too far forward on any one frame. This yields the version of Game::UpdateGame in Listing 1.5. While you aren’t updating the position of the paddle or ball just yet, you are at least calculating the delta time value.

Listing 1.5 Game::UpdateGame Implementation

void Game::UpdateGame()
{
   // Wait until 16ms has elapsed since last frame
   while (!SDL_TICKS_PASSED(SDL_GetTicks(), mTicksCount + 16))
      ;

   // Delta time is the difference in ticks from last frame
   // (converted to seconds)
   float deltaTime = (SDL_GetTicks() - mTicksCount) / 1000.0f;
   
   // Clamp maximum delta time value
   if (deltaTime > 0.05f)
   {
      deltaTime = 0.05f;
   }

   // TODO: Update objects in game world as function of delta time!
}

Updating the Paddle’s Position

In Pong, the player controls the position of the paddle based on input. Suppose you want the W key to move the paddle up and the S key to move the paddle down. Pressing neither key or both keys should mean the paddle doesn’t move at all.

You can make this concrete by using a mPaddleDir integer member variable that’s set to 0 if the paddle doesn’t move, -1 if if the paddle moves up (negative y), and 1 if the paddle moves down (positive y).

Because the player controls the position of the paddle via keyboard input, you need code in ProcessInput that updates mPaddleDir based on the input:

mPaddleDir = 0;
if (state[SDL_SCANCODE_W])
{
   mPaddleDir -= 1;
}
if (state[SDL_SCANCODE_S])
{
   mPaddleDir += 1;
}

Note how you add and subtract from mPaddleDir, which ensures that if the player presses both keys, mPaddleDir is zero.

Next, in UpdateGame, you can add code that updates the paddle based on delta time:

if (mPaddleDir != 0)
{
   mPaddlePos.y += mPaddleDir * 300.0f * deltaTime;
}

Here, you update the y position of the paddle based on the paddle direction, a speed of 300.0f pixels/second, and delta time. If mPaddleDir is -1, the paddle will move up, and if it’s 1, it’ll move down.

One problem is that this code allows the paddle to move off the screen. To fix this, you can add boundary conditions for the paddle’s y position. If the position is too high or too low, move it back to a valid position:

if (mPaddleDir != 0)
{
   mPaddlePos.y += mPaddleDir * 300.0f * deltaTime;
   // Make sure paddle doesn't move off screen!
   if (mPaddlePos.y < (paddleH/2.0f + thickness))
   {
      mPaddlePos.y = paddleH/2.0f + thickness;
   }
   else if (mPaddlePos.y > (768.0f - paddleH/2.0f - thickness))
   {
      mPaddlePos.y = 768.0f - paddleH/2.0f - thickness;
   }
}

Here, the paddleH variable is a constant that describes the height of the paddle. With this code in place, the player can now move the paddle up and down, and the paddle can’t move offscreen.

Updating the Ball’s Position

Updating the position of the ball is a bit more complex than updating the position of the paddle. First, the ball travels in both the x and y directions, not just in one direction. Second, the ball needs to bounce off the walls and paddles, which changes the direction of travel. So you need to both represent the velocity (speed and direction) of the ball and perform collision detection to determine if the ball collides with a wall.

To represent the ball’s velocity, add another Vector2 member variable called mBallVel. Initialize mBallVel to (-200.0f, 235.0f), which means the ball starts out moving −200 pixels/second in the x direction and 235 pixels/second in the y direction. (In other words, the ball moves diagonally down and to the left.)

To update the position of the ball in terms of the velocity, add the following two lines of code to UpdateGame:

mBallPos.x += mBallVel.x * deltaTime;
mBallPos.y += mBallVel.y * deltaTime;

This is like updating the paddle’s position, except now you are updating the position of the ball in both the x and y directions.

Next, you need code that bounces the ball off walls. The code for determining whether the ball collides with a wall is like the code for checking whether the paddle is offscreen. For example, the ball collides with the top wall if its y position is less than or equal to the height of the ball.

The important question is: what to do when the ball collides with the wall? For example, suppose the ball moves upward and to the right before colliding against the top wall. In this case, you want the ball to now start moving downward and to the right. Similarly, if the ball hits the bottom wall, you want the ball to start moving upward. The insight is that bouncing off the top or bottom wall negates the y component of the velocity, as shown in Figure 1.7(a). Similarly, colliding with the paddle on the left or wall on the right should negate the x component of the velocity.

Figure 1.7

Figure 1.7 (a) The ball collides with the top wall so starts moving down. (b) The y difference between the ball and paddle is too large

For the case of the top wall, this yields code like the following:

if (mBallPos.y <= thickness)
{
   mBallVel.y *= -1;
}

However, there’s a key problem with this code. Suppose the ball collides with the top wall on frame A, so the code negates the y velocity to make the ball start moving downward. On frame B, the ball tries to move away from the wall, but it doesn’t move far enough. Because the ball still collides with the wall, the code negates the y velocity again, which means the ball starts moving upward. Then on every subsequent frame, the code keeps negating the ball’s y velocity, so it is forever stuck on the top wall.

To fix this issue of the ball getting stuck, you need an additional check. You want to only negate the y velocity if the ball collides with the top wall and the ball is moving toward the top wall (meaning the y velocity is negative):

if (mBallPos.y <= thickness && mBallVel.y < 0.0f)
{
   mBallVel.y *= -1;
}

This way, if the ball collides with the top wall but is moving away from the wall, you do not negate the y velocity.

The code for colliding against the bottom and right walls is very similar to the code for colliding against the top wall. Colliding against the paddle, however, is slightly more complex. First, you calculate the absolute value of the difference between the y position of the ball and the y position of the paddle. If this difference is greater than half the height of the paddle, the ball is too high or too low, as shown earlier in Figure 1.7(b). You also need to check that the ball’s x-position lines up with the paddle, and the ball is not trying to move away from the paddle. Satisfying all these conditions means the ball collides with the paddle, and you should negate the x velocity:

if (
    // Our y-difference is small enough
    diff <= paddleH / 2.0f &&
    // Ball is at the correct x-position
    mBallPos.x <= 25.0f && mBallPos.x >= 20.0f &&
    // The ball is moving to the left
    mBallVel.x < 0.0f)
{
   mBallVel.x *= -1.0f;
}

With this code complete, the ball and paddle now both move onscreen, as in Figure 1.8. You have now completed your simple version of Pong!

Figure 1.8

Figure 1.8 Final version of Pong

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020