Gaming Architecture Unit - II
Gaming Architecture Unit - II
Unit -II
Architecture of a Game
Graphics Engine
Sound/Audio Engine
I/O Devices
The devices which are used for inputting the data and the
programs in the computer are known as Input Devices.
Input device can read data and convert them to a form that
a computer can use. Output Devices can generate the
finished product of machine processing into a form
usable/readable by humans. For a game, there should have
to be a strong interaction between the user and the game
he/she is playing. So for this the peripheral devices like
mouse, keyboard, joysticks and monitors play a major role
to make the game interactive.
Whatever your favorite video game is, it’s thanks to a game engine that helps such a marvel to be created.
Let’s get to know more about game engines and which ones are popular in game development today!
Where’s the fun in the technological world today without games? From RPGs to simulations, a lot of
hobbyists have created such a great demand for the next big gaming wonder. Because of such demand,
the industry continues to see innovative technological tools here and there to suffice what the people
want.
The technology stacks in creating games today are way beyond how they were years ago. The game
engines can now answer the common questions on how games are made. Through this tool and some
expertise in the required programming languages, software developers can champion a fully-fledged
game.
On that note, game developers are also in high demand. A powerful team with expertise in game engines
and graphic design, among others, is what a tech startup or company needs to blast a game out in the
market. But what is a game engine, and what are the things we need to know about it? Let’s find out!
A game engine is a software development environment mainly for creating video games. Other
variations for this industry term are game architecture, game framework, or simply, game frame.
The main functionalities for game engines often include 2D or 3D graphics rendering, physics engine,
animation, artificial intelligence, sound, and streaming among others.
As suggested, this is a platform that is used to create different types of video games with varying
programming languages. It’s just like any other IDE but equipped with settings and configurations to
allow seamless game development. This, therefore, leads us to what these components are.
Rendering Engine
Rendering engines or the graphic engine is a subcomponent of a game engine. It focuses on the 2D or 3D
rendering of the game’s graphics. A good game engine should have a rendering engine that is compatible
with different import formats.
Whether it’s 2D or 3D, having a graphic component that blends the cosmetics of a game well is essential.
Artificial Intelligence
Artificial Intelligence yields a significant impact on a game’s overall performance and logic. When
creating a game, the AI engine automatically provides recommendations based on the player’s behavior
in-game.
For example, a hero in a multiplayer battle arena game gets close to an enemy tower. The tower attacks
the hero as a reaction when it is within range. Consequently, the hero loses some life points from the
tower’s attack.
These logics are implemented by creating scripts that have been written and designed by expert AI
software engineers. We could say that the scripts respond based on the game behavior in an overall setup.
Physics Engine
And so we thought we could leave Physics at school. That’s where we’re wrong. A physics engine is a
piece of software that is very important, especially for simulation games. This is a subcomponent relative
to designing and developing simulations of real-life activities, movements, and reactions. These include
velocity, acceleration, fluidity, and projectile motions, among others.
Physics engines are used mostly for video games with real-life actions and real-time reactions. Grand
Theft Auto is one great example of the use of physics as a game engine. The collisions of vehicles and
gravity when falling give us a visual simulation of real-life action-reaction instances.
Sound Engine
Sound or audio engine controls the sound effects generated by the in-game interactions. These are audio
files integrated into the game logic through software applications or SDKs available. This loads optimizes
and plays the sound files dedicated to each action in the game.
Networking
The age of the internet allowed a more interactive gaming experience using networking. The network
engine supports multiplayer or social gaming connecting you with other users to enjoy the game together.
Overall, these engines work together to complete a fully functioning game for every user. One or two of
these might not be required depending on the game being developed. Regardless, this software tool is
recommended for companies and developers to use.
Another demand that this niche has created is effective development tools for game developers and
companies to use. Some are platform exclusive, and some are not. Game engine companies have
continued to evolve, considering the recommended updates for games.
We owe it to these game engine companies for creating tools for developers to use whatever games we
desire. Here are some of the most popular game engines globally.
Unity
On top of our list is the Unity game engine. This one is a favorite since it is easier to use for new and
experienced game developers.
Unity caters to multiple platforms with regard to the interactive 3D gaming experience. Through Unity,
you can develop high-quality games with optimal performance in any game genre you want!
Additionally, Unity has a free version for personal use. Enterprise users can subscribe monthly to attain
more functionalities and business branding capabilities. Lara Croft Go and Pillars of Eternity are some
examples of games created using Unity.
Unreal
Unreal is another popular game engine by Epic Games that professional game developers use. The
reason for its popularity is because it is easy to use and well-documented. It’s been available since 1998
and is continuously updated to give the best game development experience.
You can create multi-platform games through Unity from console to mobile (Android and iOS). Beyond
the game industry, it’s also used in automotive. Games like Fortnite and Mortal Kombat Mobile are
created using the Unreal game engine.
Amazon Lumberyard
As the name suggests, Lumberyard is an Amazon-owned game engine. They market it as “Free.
Powerful. Fully Customizable.” Lumberyard also offers seamless hosting through AWS and integrating
on Twitch aside from the main game development.
Amazon Lumberyard is also recommended when you are going for a multiplayer game.
ARKit
ARKitis somewhat different from the other items on this list. This framework introduced by iOS11
allows you to create brilliant augmented reality (AR) experiences on iOS devices.
It’s mostly popular among iOS developers because of its top-notch AR capabilities. These include face
detection and tracking, object detection, image tracking, position tracking, and orientation tracking.
GameMaker
GameMaker makes it easy for game makers to create and design games. Why? This Yoyo Games
platform only uses point-and-click to create games! No coding is needed at the bare minimum.
The good thing though, is that having a programming background could exponentially improve your
game. While GameMaker is free, you’d have to subscribe to their premium offers to leverage the platform
at max.
Currently, there are millions of game applications available across mobile platforms alone. When we add
PC and console games, it’s an entire myriad of creative possibilities. These numbers account for the
demand of game developers across the globe. Simultaneously, companies are also kart racing their way
to becoming the next big game in the tracks.
At Full Scale, we help you realize the software product of your dreams! Through our Guided
Development format, you can hire an entire team from us while in control of the vision of your product.
Aside from software development, our experts in product management and artificial intelligence can help
you build simple mobile game apps. Get a free consultation when you contact us! We can help you
rev up your engines.
Video Game Mechanics Explained
One of the biggest reasons why games reach huge audiences today
has to do with game mechanics. In order to better understand what
game mechanics are, we have to think of a game system. Imagine
there are various sub-parts that this system controls. To picture this
better, you can examine the diagram below:
We will describe the various pieces that make up the game mechanics
in the next few sections below.
Game System
As you can see in the diagram above, the game system takes on the
following tasks:
Resources
The Resources describe the necessary files for the game located on the
hard disk.
Game Model
The game model is the state of the game graphics, music and text
files loaded into memory from the resource.
Image files are stored in memory or in the texture memory of the
video card.
Section, score, etc. information is kept in variables and data
structures within the game model.
Upload and Save
This is the part that takes the graphics, music and other information
from the source and puts it into the memory (game model) and
undertakes the process of saving it back to the source in case of
changes in scores, when the game is saved – or the save state – or
when the game is recorded.
Graphics
This is the most important and hardest part of the game in my opinion.
Because it is impossible to have a game without visuals (unless you
are creating an old school text-based video game). This part is
responsible for painting the screen and the following:
User Input
A game without interaction would be like watching a movie. User
Interaction is definitely one of the sine qua non of game mechanics
that connects users to the game. The system is constantly interacting
with the user. Keyboards, mice, cameras, and so forth are all capable
of taking in user input. User input is the part of the game mechanic
where we’re going to use the hardware and equipment that lets the
user interact with the game. User input allows a player to:
Hardware
Gamers love the various elements of a game and are always looking
for better graphics, music, physics and artificial intelligence. For all of
this to happen (and for games to get more complex over time), one of
two conditions must be met:
Graphics cards
Processors
Motherboards
Sound cards
Monitors, speakers and other input devices
Read: Unity Game Programming: Normalizing Game Speed Across
Devices.
Best Programming Languages for Game
Development
Programming languages are a computer language that lets
programmers develop commands and software in a certain standard
form. Thanks to programming languages, it is possible to control what
kind of output a computer can give in different situations. In short,
computers and humans can communicate efficiently thanks to
programming languages.
Depending on what you want to create, you can develop games with
pretty much all programming languages, albeit to different degrees.
There will be those who insist you learn C++, especially if you want to
code games for consoles like the PlayStation 5 or Xbox. This, however,
is absolutely not true. You can make great games
with JavaScript, C#, Python (thanks to modules like PyGame) or
even C. A choice-based adventure game that only works on the
console screen can be great fun. However, if you want to program
games beyond that and that are capable of being more professional
and reaching a larger audience, continue reading.
C++
Since C++ is a high-level language that will teach you the basics of
object-oriented programming (OOP), it’s a good idea to learn it. It is
also the language used to create console and Windows games. Also, it
uses OpenGL or a similar framework (We cover OpenGL in greater
detail later in this guide).
C#
The benefit of C# for video game development lies in the XNA
framework. This is a set of tools and workspaces by Microsoft that are
particularly suitable for developing games on Xbox or Windows
platforms.
If you compare C++ and C#, you might consider this example: C++ is
like a manual transmission car; C#, on the other hand, is like an
automatic transmission car. Let’s consider the Unity game engine. If
you use the Unity game engine, you have to code your game scripts in
C#. However, the core of this game engine was developed using C++
code.
The platform you target, the game you want to make, the game engine
you will use, etc. will affect the language you choose. No matter,
however, learning C# for game development would be a great idea.
Java
Game programmers often use Java because Java supports
multithreading and sockets. Multithreading uses less memory and
makes the most of available CPU resources without blocking the user
while intensive processes are running in the background. Sockets help
in the creation of multiplayer games. Also, Java runs in a virtual
machine (the JVM) so the game is easier to deploy to different
platforms.
JavaScript
Making games for browsers is very different than making games for
consoles. If you want to use 3D graphics or complex graphics and a
content management system, you will also need SVG or WebGL.
Moreover, there are great game engines that you can use JavaScript to
develop games with. One example of this is PhaserJS.
The APIs we will use in our games will be libraries that allow us to take
advantage of them by providing an interface to the graphics and sound
hardware. For example OpenGL, GLUT, GLU
DirectX (Direct3D, DirectDraw, DirectShow, DirectInput, DirectPlayer, D
irectSound, DirectMusic), Java2D, Java3D, JavaMusic, JavaNET, JavaMed
ia, and FMOD are all examples of game development APIs.
main(){
initializeAwindowPlease( );
glClear(GL_COLOR_BUFFER_BIT)
glBegin(GL_POLYGON)
glEnd( );
glFlush( )
UpdateTheWindowAndCheckForEvents( );
The first and most important thing to note about the file functions
is that they are limited - in general and by default - to
the sandbox. What this means is that GameMaker cannot save or
load files from anywhere that is not part of the game bundle or
the local storage for the device without explicit input from the
user, and even then this input is limited to only Windows, macOS
and Ubuntu (Linux) target platforms.
IMPORTANT! It is possible to turn off the sandboxing, however, on the
Desktop targets (Windows, macOS, and Ubuntu (Linux)) by checking
the Disable file system sandbox option in the Game Options for the
target platform. You do this at your own risk, and while this will open
up file saving and loading and permit you to access files anywhere on
the given system, it may still be limited by the OS permissions, and
you will not be able to write to the program_directory folder.
The File Bundle - this is where all the files that are packaged with
the executable game are stored, including the files that you have
added to the Included Files asset list from the GameMaker IDE
(which are the external files that you want packaged with the
game).
When your game is sandboxed, the two target areas - the bundle
directory and the local storage area - are available on each target
platform, but on each one they will work slightly differently.
However GameMaker has abstracted out the main essence of
what can and can't be done, making it easier to re-target games
to multiple environments.
Using these two simple rules we can now see how the following
functions work (these are examples to help you to visualise the
process for the different functions available):
You should also know that each target platform has its own save
area where files and directories can be written to and read from.
Below is a list of those areas for each target when sandboxed:
Windows: Windows has all files in the %localappdata%\<Game
Name> directory (on Windows 7 this is the /Users/<User
Name>/AppData/Local/<Game Name> directory).
Learn about Game File Formats and APIs that can create
and open Game files
Game file category ncludes essential video game files or files referenced by video games to run a game
successfully on a supported devices such as laptop, mobile, XBox and Play Stations. Game ROMs, which are
software copies of old age games developed for other old systems are also come under the game files category.
Game Loop
Motivation
If there is one pattern this book couldn’t live without, this is it. Game loops are the
quintessential example of a “game programming pattern”. Almost every game has one,
no two are exactly alike, and relatively few programs outside of games use them.
To see how they’re useful, let’s take a quick trip down memory lane. In the olden days
of computer programming when everyone had beards, programs worked like your
dishwasher. You dumped a load of code in, pushed a button, waited, and got results
out. Done. These were batch mode programs — once the work was done, the program
stopped.
Ada Lovelace and Rear Admiral Grace Hopper had honorary beards.
You still see these today, though thankfully we don’t have to write them on punch
cards anymore. Shell scripts, command line programs, and even the little Python script
that turns a pile of Markdown into this book are all batch mode programs.
> GO IN
YOU ARE INSIDE A BUILDING, A WELL HOUSE FOR A LARGE SPRING.
You could have a live conversation with the program. It waited for your input, then it
would respond to you. You would reply back, taking turns just like you learned to do in
kindergarten. When it was your turn, it sat there doing nothing. Something like:
while (true)
{
char* command = readCommand();
handleCommand(command);
}
This loops forever, so there’s no way to quit the game. A real game would do something
like while (!done) and set done to exit. I’ve omitted that to keep things simple.
Event loops
Modern graphic UI applications are surprisingly similar to old adventure games once
you shuck their skin off. Your word processor usually just sits there doing nothing until
you press a key or click something:
while (true)
{
Event* event = waitForEvent();
dispatchEvent(event);
}
The main difference is that instead of text commands, the program is waiting for user
input events — mouse clicks and key presses. It still works basically like the old text
adventures where the program blocks waiting for user input, which is a problem.
Unlike most other software, games keep moving even when the user isn’t providing
input. If you sit staring at the screen, the game doesn’t freeze. Animations keep
animating. Visual effects dance and sparkle. If you’re unlucky, that monster keeps
chomping on your hero.
Most event loops do have “idle” events so you can intermittently do stuff without user
input. That’s good enough for a blinking cursor or a progress bar, but too rudimentary
for games.
This is the first key part of a real game loop: it processes user input, but doesn’t wait
for it. The loop always keeps spinning:
while (true)
{
processInput();
update();
render();
}
We’ll refine this later, but the basic pieces are here. processInput() handles any
user input that has happened since the last call. Then, update() advances the game
simulation one step. It runs AI and physics (usually in that order).
Finally, render() draws the game so the player can see what happened.
As you might guess from the name, update() is a good place to use the Update
Method pattern.
The common terms for one crank of the game loop are “tick” and “frame”.
Meanwhile, the player’s actual clock is ticking. If we measure how quickly the game
loop cycles in terms of real time, we get the game’s “frames per second”. If the game
loop cycles quickly, the FPS is high and the game moves smoothly and quickly. If it’s
slow, the game jerks along like a stop motion movie.
With the crude loop we have now where it just cycles as quickly as it can, two factors
determine the frame rate. The first is how much work it has to do each frame. Complex
physics, a bunch of game objects, and lots of graphic detail all will keep your CPU and
GPU busy, and it will take longer to complete a frame.
The second is the speed of the underlying platform. Faster chips churn through more
code in the same amount of time. Multiple cores, GPUs, dedicated audio hardware, and
the OS’s scheduler all affect how much you get done in one tick.
Older games were carefully coded to do just enough work each frame so that the game
ran at the speed the developers wanted. But if you tried to play that same game on a
faster or slower machine, then the game itself would speed up or slow down.
This is why old PCs used to have “turbo” buttons. New PCs were faster and couldn’t play
old games because the games would run too fast. Turning the turbo button off would
slow the machine down and make old games playable.
These days, though, few developers have the luxury of knowing exactly what hardware
their game will run on. Instead, our games must intelligently adapt to a variety of
devices.
This is the other key job of a game loop: it runs the game at a consistent speed despite
differences in the underlying hardware.
The Pattern
A game loop runs continuously during gameplay. Each turn of the loop, itprocesses
user input without blocking, updates the game state, and renders the game. It
tracks the passage of time to control the rate of gameplay.
When to Use It
Using the wrong pattern can be worse than using no pattern at all, so this section is
normally here to caution against over-enthusiasm. The goal of design patterns isn’t to
cram as many into your codebase as you can.
But this pattern is a bit different. I can say with pretty good confidence that
you will use this pattern. If you’re using a game engine, you won’t write it yourself, but
it’s still there.
For me, this is the difference between an “engine” and a “library”. With libraries, you
own the main game loop and call into the library. An engine owns the loop and calls
into your code.
You might think you won’t need this if you’re making a turn-based game. But even
there, though the game state won’t advance until the user takes their turn,
the visual and audible states of the game usually do. Animation and music keep
running even when the game is “waiting” for you to take your turn.
Keep in Mind
The loop we’re talking about here is some of the most important code in your game.
They say a program spends 90% of its time in 10% of the code. Your game loop will be
firmly in that 10%. Take care with this code, and be mindful of its efficiency.
Made up statistics like this are why “real” engineers like mechanical and electrical
engineers don’t take us seriously.
Sometimes, you can take control and make your loop the only one. For example, if
you’re writing a game against the venerable Windows API, your main() can just have
a game loop. Inside, you can call PeekMessage() to handle and dispatch events from
the OS. Unlike GetMessage(), PeekMessage() doesn’t block waiting for user input,
so your game loop will keep cranking.
Other platforms don’t let you opt out of the event loop so easily. If you’re targeting a
web browser, the event loop is deeply built into browser’s execution model. There, the
event loop will run the show, and you’ll use it as your game loop too. You’ll call
something like requestAnimationFrame() and it will call back into your code to
keep the game running.
Sample Code
For such a long introduction, the code for a game loop is actually pretty
straightforward. We’ll walk through a couple of variations and go over their good and
bad points.
The game loop drives AI, rendering, and other game systems, but those aren’t the
point of the pattern itself, so we’ll just call into fictitious methods here. Actually
implementing render(), update() and others is left as a (challenging!) exercise for
the reader.
while (true)
{
processInput();
update();
render();
}
The problem with it is you have no control over how fast the game runs. On a fast
machine, that loop will spin so fast users won’t be able to see what’s going on. On a
slow machine, the game will crawl. If you have a part of the game that’s content-heavy
or does more AI or physics, the game will actually play slower there.
The sleep() here makes sure the game doesn’t run too fast if it processes a frame
quickly. It doesn’t help if your game runs too slowly. If it takes longer than 16ms to
update and render the frame, your sleep time goes negative. If we had computers that
could travel back in time, lots of things would be easier, but we don’t.
Instead, the game slows down. You can work around this by doing less work each
frame — cut down on the graphics and razzle dazzle or dumb down the AI. But that
impacts the quality of gameplay for all users, even ones on fast machines.
If step two takes longer than step one, the game slows down. If it takes more than 16
ms of processing to advance game time by 16ms, it can’t possibly keep up. But if we
can advance the game by more than 16ms of game time in a single step, then we can
update the game less frequently and still keep up.
The idea then is to choose a time step to advance based on how much real time passed
since the last frame. The longer the frame takes, the bigger steps the game takes. It
always keeps up with real time because it will take bigger and bigger steps to get
there. They call this a variable or fluid time step. It looks like:
Each frame, we determine how much real time passed since the last game update
(elapsed). When we update the game state, we pass that in. The engine is then
responsible for advancing the game world forward by that amount of time.
Say you’ve got a bullet shooting across the screen. With a fixed time step, in each
frame, you’ll move it according to its velocity. With a variable time step, you scale that
velocity by the elapsed time. As the time step gets bigger, the bullet moves farther in
each frame. That bullet will get across the screen in the same amount of real time
whether it’s twenty small fast steps or four big slow ones. This looks like a winner:
But, alas, there’s a serious problem lurking ahead: we’ve made the game non-
deterministic and unstable. Here’s one example of the trap we’ve set for ourselves:
“Deterministic” means that every time you run the program, if you give it the same
inputs, you get the exact same outputs back. As you can imagine, it’s much easier to
track down bugs in deterministic programs — find the inputs that caused the bug the
first time, and you can cause it every time.
Say we’ve got a two-player networked game and Fred has some beast of a gaming
machine while George is using his grandmother’s antique PC. That aforementioned
bullet is flying across both of their screens. On Fred’s machine, the game is running
super fast, so each time step is tiny. We cram, like, 50 frames in the second it takes the
bullet to cross the screen. Poor George’s machine can only fit in about five frames.
This means that on Fred’s machine, the physics engine updates the bullet’s position 50
times, but George’s only does it five times. Most games use floating point numbers,
and those are subject to rounding error. Each time you add two floating point
numbers, the answer you get back can be a bit off. Fred’s machine is doing ten times
as many operations, so he’ll accumulate a bigger error than George. The same bullet
will end up in different places on their machines.
This is just one nasty problem a variable time step can cause, but there are more. In
order to run in real time, game physics engines are approximations of the real laws of
mechanics. To keep those approximations from blowing up, damping is applied. That
damping is carefully tuned to a certain time step. Vary that, and the physics gets
unstable.
“Blowing up” is literal here. When a physics engine flakes out, objects can get
completely wrong velocities and launch themselves into the air.
This instability is bad enough that this example is only here as a cautionary tale and to
lead us to something better…
Play catch up
One part of the engine that usually isn’t affected by a variable time step isrendering.
Since the rendering engine captures an instant in time, it doesn’t care how much time
advanced since the last one. It renders things wherever they happen to be right then.
This is more or less true. Things like motion blur can be affected by time step, but if
they’re a bit off, the player doesn’t usually notice.
We can use this fact to our advantage. We’ll update the game using a fixed time step
because that makes everything simpler and more stable for physics and AI. But we’ll
allow flexibility in when we render in order to free up some processor time.
It goes like this: A certain amount of real time has elapsed since the last turn of the
game loop. This is how much game time we need to simulate for the game’s “now” to
catch up with the player’s. We do that using a series of fixed time steps. The code looks
a bit like:
processInput();
render();
}
There’s a few pieces here. At the beginning of each frame, we update lag based on
how much real time passed. This measures how far the game’s clock is behind
compared to the real world. We then have an inner loop to update the game, one fixed
step at a time, until it’s caught up. Once we’re caught up, we render and start over
again. You can visualize it sort of like this:
Note that the time step here isn’t the visible frame rate anymore.MS_PER_UPDATE is
just the granularity we use to update the game. The shorter this step is, the more
processing time it takes to catch up to real time. The longer it is, the choppier the
gameplay is. Ideally, you want it pretty short, often faster than 60 FPS, so that the
game simulates with high fidelity on fast machines.
But be careful not to make it too short. You need to make sure the time step is greater
than the time it takes to process an update(), even on the slowesthardware.
Otherwise, your game simply can’t catch up.
I left it out here, but you can safeguard this by having the inner update loop bail after a
maximum number of iterations. The game will slow down then, but that’s better than
locking up completely.
Fortunately, we’ve bought ourselves some breathing room here. The trick is that
we’ve yanked rendering out of the update loop. That frees up a bunch of CPU time. The
end result is the game simulates at a constant rate using safe fixed time steps across a
range of hardware. It’s just that the player’s visible window into the game gets
choppier on a slower machine.
Here’s a timeline:
As you can see, we update at a nice tight, fixed interval. Meanwhile, we render
whenever we can. It’s less frequent than updating, and it isn’t steady either. Both of
those are OK. The lame part is that we don’t always render right at the point of
updating. Look at the third render time. It’s right between two updates:
Imagine a bullet is flying across the screen. On the first update, it’s on the left side.
The second update moves it to the right side. The game is rendered at a point in time
between those two updates, so the user expects to see that bullet in the center of the
screen. With our current implementation, it will still be on the left side. This means
motion looks jagged or stuttery.
Conveniently, we actually know exactly how far between update frames we are when
we render: it’s stored in lag. We bail out of the update loop when it’s less than the
update time step, not when it’s zero. That leftover amount? That’s how far into the next
frame we are.
render(lag / MS_PER_UPDATE);
Of course, it may turn out that that extrapolation is wrong. When we calculate the next
frame, we may discover the bullet hit an obstacle or slowed down or something. We
rendered its position interpolated between where it was on the last frame and where
we think it will be on the next frame. But we don’t know that until we’ve actually done
the full update with physics and AI.
Design Decisions
Despite the length of this chapter, I’ve left out more than I’ve included. Once you
throw in things like synchronizing with the display’s refresh rate, multithreading, and
GPUs, a real game loop can get pretty hairy. At a high level, though, here are a few
questions you’ll likely answer:
Now, you may need to think not only about making your game look great, but also use
as little CPU as possible. There will likely be an upper bound to performance where
you let the CPU sleep if you’ve done all the work you need to do in a frame.
This is what you’re likely to do for PC games (though even those are increasingly being
played on laptops). Your game loop will never explicitly tell the OS to sleep. Instead,
any spare cycles will be spent cranking up the FPS or graphic fidelity.
This gives you the best possible gameplay experience but, it will use as much power as
it can. If the player is on a laptop, they’ll have a nice lap warmer.
Mobile games are often more focused on the quality of gameplay than they are on
maximizing the detail of the graphics. Many of these games will set an upper limit on
the frame rate (usually 30 or 60 FPS). If the game loop is done processing before that
slice of time is spent, it will just sleep for the rest.
This gives the player a “good enough” experience and then goes easy on their battery
beyond that.
This was our first sample code. You just run the game loop as fast as you can.
o Still quite simple. It’s only one line of code more than the probably-too-simple-to-
actually-work example. In most game loops, you will likely do synchronization anyway.
You will probably double buffer your graphics and synchronize the buffer flip to the
refresh rate of the display.
o It’s power-friendly. This is a surprisingly important consideration for mobile games.
You don’t want to kill the user’s battery unnecessarily. By simply sleeping for a few
milliseconds instead of trying to cram ever more processing into each tick, you save
power.
o The game doesn’t play too fast. This fixes half of the speed concerns of a fixed loop.
o The game can play too slowly. If it takes too long to update and render a game frame,
playback will slow down. Because this style doesn’t separate updating from rendering,
it’s likely to hit this sooner than more advanced options. Instead of just
dropping rendering frames to catch up, gameplay will slow down.
Variable time step:
I’ll put this in here as an option in the solution space with the caveat that most game
developers I know recommend against it. It’s good to rememberwhy it’s a bad idea,
though.
o It adapts to playing both too slowly and too fast. If the game can’t keep up with real
time, it will just take larger and larger time steps until it does.
o It makes gameplay non-deterministic and unstable. And this is the real problem, of
course. Physics and networking in particular become much harder with a variable time
step.
Fixed update time step, variable rendering:
The last option we covered in the sample code is the most complex, but also the most
adaptable. It updates with a fixed time step, but it can drop renderingframes if it needs
to to catch up to the player’s clock.
o It adapts to playing both too slowly and too fast. As long as the game can update in
real time, the game won’t fall behind. If the player’s machine is top-of-the-line, it will
respond with a smoother gameplay experience.
o It’s more complex. The main downside is there is a bit more going on in the
implementation. You have to tune the update time step to be both as small as possible
for the high-end, while not being too slow on the low end.