KEMBAR78
Gaming Architecture Unit - II | PDF | Computer Graphics | Computer File
0% found this document useful (0 votes)
8 views40 pages

Gaming Architecture Unit - II

Unit II covers the design and architecture of game engines, detailing essential components such as graphics, sound, rendering, I/O devices, and APIs. It explains the role of game engines in creating interactive experiences and highlights popular engines like Unity and Unreal. The document also discusses game mechanics, including user input, graphics, sound, and artificial intelligence, emphasizing their importance in enhancing gameplay.

Uploaded by

kishorkolhe2188
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views40 pages

Gaming Architecture Unit - II

Unit II covers the design and architecture of game engines, detailing essential components such as graphics, sound, rendering, I/O devices, and APIs. It explains the role of game engines in creating interactive experiences and highlights popular engines like Unity and Unreal. The document also discusses game mechanics, including user input, graphics, sound, and artificial intelligence, emphasizing their importance in enhancing gameplay.

Uploaded by

kishorkolhe2188
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

UNIT II:

GAME ENGINE DESIGN


Game engine architecture, Engine support systems, Resources and File systems, Game loop and real-time
simulation, Human Interface devices, Collision and rigid body dynamics, Game profiling.

Unit -II

Understanding Game Architecture


People who are creative and artistic, find devotion in
sharing their dreams, thoughts and visions. A Painter does
so by painting, while a Musician creates music. Similarly,
programmers want to automate and make your life easy,
and game designers want to make their thoughts and ideas
to come to life through their games.
Every standard game consists of some series of levels:
embedded and closely related with the storyline of the
game, action and adventure sequences to live, spectacular
visuals to experience, and they challenge our mental
abilities by exploring and bringing out our tactical &
strategy making skills. Games are the most unique, of all
entertainment mediums because of its interactive power
with its audience.
Most of the games, give the player(s) the most important
role of the story: the Hero. Which is a great way to invlove
the player into the gameplay.

Architecture of a Game

The architecture and structure of a game is similar to that


of a software. But it does have some additional components
which makes it different from a software. Every game has
the following components:
 Graphics Engine
 Sound/Audio Engine
 Rendering & Vision-Input Engine
 I/O Devices (like, Mouse, keyboard, speaker, monitor
etc)
 DLL files and Drivers/Device APIs

All these above mentioned components combine together


to make a game playable to its full extent. Before
discussing each of them, let's just clear what an engine is.
Engines are the self-processing component(s) of a
complete process that are driving automatically behind the
original process.

Graphics Engine

A graphic engine is a software which in association with an


application program helps to draw graphics on your
computer's display device.
The word engine in the computer field refers to a software
which helps performing some definite type of processing on
programs, such as text-to-speech engine, a database
engine, a layout engine and a graphics engine. Graphics
engine helps to make your game's graphics better by
increasing the resolution and increasing the number of
pixels per unit area. This engine also makes your game's
scenes clear and run smooth.

Sound/Audio Engine

The audio/sound engine is the component that consists of


algorithms for dealing with sound and in-built programs are
written into it to handle the sound effects embedded in the
game. It has the capability to perform calculations using
the CPU, or on any dedicated ASIC (Application Specific
Integrated Circuit). Abstraction APIs, such as Open-AL,
SDL Audio, X-Audio 2, Web Audio, etc. can be available
within this engine.

Rendering and Vision-Input Engine


The rendering engine along with vision input system
produces 3D animated graphics, using different techniques,
like rasterization and ray-tracing. Being programmed and
compiled to be executed on any CPU or GPU
straightforwardly, majority of rendering engines are
developed upon one or more rendering APIs like Direct3D
and/or OpenGL that offers a software abstraction layer for
the Graphics Processing Unit (GPU).
Low-level libraries like DirectX or OpenGL are popularly
incorporated in games because they supply the hardware-
independent access to different computer hardware. These
hardware devices can be input devices like mouse,
keyboard, and joystick; network devices like NIC and also to
sound cards.

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.

DLL files and Drivers/Device APIs


A DLL (Dynamic Link Library) file, is a type of file which
includes instructions written in the form of programs which
can be called or used by other programs for performing
certain tasks. In this manner, different programs can share
the abilities and characteristics that have been
programmed into a single file.
These system level files play a supporting role to build the
architecture of the game and help to make it perform well.
You might have noticed that, if you have installed a game
which you want to play and you click the executable(.exe
file) to run the game, and just before starting of the game,
an error message pops up, with a message
- <particular_dll_name>.dll is missing". These files are
the supporting files that your system should have to make
the game work.
Again, a device API can be defined as API (Application
Programming Interface) which lets the developers to
create any application which can ultimately interact with
hardware devices plugged or installed with your system. A
device API normally provides end users to employ their
plugged or associated hardware for interacting with the
system. Majority of the games (popular) need these device
drivers and APIs to make the game work with all its
components running successfully.
These five components make the architecture of a game
both internally as well as externally.
What is a Game Engine?

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!

What is Game Engine?

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.

Components of a Game Engine

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.

Related Video: What Is Artificial Intelligence

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.

Most Popular Game Engines

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:

 Handles the loading and saving of files.


 It then enables the intro animation to run using the audio and
graphic elements.
 While the game interface is being used, user input ensures that the
graphics and sound parts work in harmony.
 Finally, the game system ensures that the graphics, sound, user
input, artificial intelligence and network parts work in harmony in
the game.

Resources
The Resources describe the necessary files for the game located on the
hard disk.

 These resources contain configuration files that describe the default


settings in which the game will run.
 If available, it contains the video file for the intro that will be played
when the game first starts.
 Contains files where the user gets information about the game
before the game begins.
 It contains the graphics, music and chapter information in the game,
alongside every other element the game will require to display audio
and visual data to the player.

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.

 Upload: Configuration files, chapter files, image files, music and


sound files, 3D model files, video files, and help files.
 Save: Score files and other documents to be saved during the game.

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:

 Playing any video,


 Displaying the game interface.
 Viewing and displaying scores, help and configuration information.
 Displaying the game’s own graphics and visual elements.

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:

 Use the Game Interface.


 Review Help Files.
 Review Score Files.
 Configure the system and game related features.
 Control the user’s character in the game.

Sound and Music


If you truly want to understand the importance of sound and music in a
video game, try turning off the sound while playing your favorite game.
You will notice that the value of the game drops significantly when
there is no sound. To me, the value of the sound is as valuable as the
graphics of the game.

 Music playing in the background


 Sound effects for collisions and movements

Artificial intelligence (AI)


Let’s consider the intelligence level of the enemies in the game. The
more humanoid they look and the more intelligent the behavior, the
more fun the game will be. It doesn’t just have to be the enemy either.
In an open world game, citizens passing by look at their wristwatches,
wipe the sweat on their foreheads in sunny weather, give way to you,
even argue with you, attack you when you treat animals badly, and so
forth. All of these elements can fall into the category of artificial
intelligence.

Network Listening and Sending


Network listening and sending is the part of the game mechanic that
allows the game to be played by more than one person, also known as
multiplayer or online play. In this part, the parties send information to
the game server and the information received by listening to the
server is updated in the game. Network listening and sending is
responsible for:

 Establishing the Session: The players who will participate in the


game agree on which protocol and on which port they will
communicate at first.
 Packet Delivery: The moves made in the game are sent to the server
in packets. Then the server distributes it to all parties after making
the necessary change.
 Package Pickup: Simultaneously, the parties are aware of the
changes made by listening to the server and reflect this to the
game.

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:

Software optimization should be practiced and new algorithms should


be developed.
Appropriate equipment and hardware should be used, including
increasing processing speed and memory.

Today, new algorithms and code optimization discoveries progress


much slower than the speed at which new hardware develops. To
combat this, instead of new algorithms, the developer should focus on
issues such as reusability, code openness, and code security
(encapsulation). To facilitate this, the hardware tries to increase the
processor speed and memory capacity as much as possible for these
new requests.

Many different categories of hardware can fall into this section,


including the following:

 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.

Since our topic is video game development, it is only natural that we


spend a little time focusing on programming languages, which we
ultimately use to create video games.

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++ is a fast compiling programming language. You also get a lot of


say in memory management. It has extensive libraries useful for
designing and powering complex graphics. There’s a lot of literature
for you to study and learn from, because it’s been the video game
programmer’s language of choice for decades, and you’ll find online
communities ready and willing to answer your questions.

It would be a lie if we said that C++ is easy to learn. It is difficult to


learn compared to other programming languages. However, it can be
useful not only because C++ games are easy to distribute on various
platforms, but also because if you know C++ you can quickly learn C#
and other object-oriented languages, including C and Java (even
though Java is not technically an OOP language). C++, C, Java, and C#
are some of the most actively used programming languages today.

To summarize, learning C++ is a good choice if you want to create


video games from scratch for multiple platforms.

Read our C++ programming tutorials.

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.

Read our C# programming tutorials.

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.

Additionally, if you want to develop applications and games for Android


platforms, Java would be a great option.

Read our Java programming tutorials.

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.

Flash animation using the programming language ActionScript was


common for browser games in the past, but Flash is no longer
supported.

Unity 3D Engine accepts Javascript. A WebGL-enabled Java engine such


as PlayCanvas, developed at MIT, allows users to simultaneously work
in the game with an online browser and publish to multiple platforms.

Moreover, there are great game engines that you can use JavaScript to
develop games with. One example of this is PhaserJS.

Read our JavaScript programming tutorials.


APIs for Game Development
What is an API? It stands for Application Programming Interface. APIs
are libraries that help us perform specific tasks with a number of
functions and methods.

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.

In particular, it is very useful for game developers to learn the OpenGL


library. With that in mind, let’s talk a little bit more about OpenGL.

OpenGL for Game Development


OpenGL resides within graphics hardware and provides an interface to
that hardware. This interface contains 250 different instruction sets.
200 of them are in the OpenGL core and the other 50 are in the
OpenGL Utility Library. You can develop 3D interactive applications
thanks to the OpenGL graphics API.

OpenGL is a platform independent API. It has been designed as an


interface that performs a command flow that is run consecutively. In
order to ensure this quality, it does not include commands such as
windowing tasks and obtaining user input, but instead benefits from
the windowing and input services provided by the platform it uses to
OpenGL. Likewise, it does not contain commands for creating high-
level 3D objects. But with the commands it provides, it can create an
automobile, plane, or molecule surface. To create the desired models
of this type with OpenGL, we make use of the points, lines, and
polygons in the small toolkit we call the geometric primitive.

Of course, the creation of a better graphics system can be built on top


of OpenGL’s core structures. OpenGL Utility Library (GLU) has many
high-level modeling features, Quadratic surfaces, NURBS curve, and
surface rendering.
What are the Operations Performed During
Rendering?
In the following 4 stages, you can briefly see what processes are
happening during the rendering process:

 Creating shapes and geometric objects with mathematical


expressions (OpenGL has tools to create primitive objects such as
point, line, polygon, image, and bitmap).
 Arrangement of objects in a three-dimensional plane and adjustment
of perspective.
 Calculating the color values of the objects and applying them to the
screen by taking into account the light and texture values.
 The conversion of the definitions and color values of all object values
to pixel values and the realization of the rasterization event.

A Simple OpenGL Code Example


Choosing so many options and performing complex operations with the
OpenGL graphics system can make OpenGL seem complex. But
basically, the structure of a program made with OpenGL is very simple.
What you’re doing is actually defining certain states and putting a
control mechanism on which objects OpenGL should render and how it
should render them.

You can actually think of OpenGL as a real-time rendering software.


Here is a sample showing how OpenGL looks in code:

main(){

initializeAwindowPlease( );

glClearColor(0.0, 0.0, 0.0, 0.0);

glClear(GL_COLOR_BUFFER_BIT)

glColor3f(1.0, 1.0, 1.0);


glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0)

glBegin(GL_POLYGON)

glVertex3f(0.25, 0.25, 0.0)

glVertex3f(0.75, 0.25, 0.0)

glVertex3f(0.75, 0.75, 0.0)

glVertex3f(0.25, 0.75, 0.0)

glEnd( );

glFlush( )

UpdateTheWindowAndCheckForEvents( );

Game Development Tutorials


First of all, thank you very much to those who have come this far. To
summarize what we have learned from our game programming tutorial
so far:

 Game development is not just about learning programming


languages and game engines.
 You have to master a lot of technology. Among the technologies we
did not mention are programs such as Adobe Premier, Adobe After
Effects, 3D Studio Max, Lightwave, Maya and Poser. Learning and
mastering each of these is only possible with experience.
 That’s why we talked about hardware and OpenGL. Love your
computer and keyboard rather than focusing on one thing. The best
and only rule of thumb to master game development is this:Be
curious, read a lot and code without fear!
Game Files
The Game Files category includes saved video game files and files
referenced by video games. It also includes game ROMs, which are
software copies of games developed for other systems, such as Super
Nintendo and Nintendo 64. These files can be played using a software
emulator.
Common game file extensions include .GAM, .SAV, and .ROM.

The File System

When using the file system functions or included


files with GameMaker it is vitally important to know exactly how
the file system works and what things are going on behind the
scenes. To that end, this section is designed to explain and clarify
exactly how things are stored, where they are stored and what
possible limits or workarounds there may be to this system.

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.

To understand the sandbox first of all you need to understand


that there are two distinct areas for files:

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).

The Save Area - this is an area of device storage that can be


safely written to by the game and the game is guaranteed that
this is a writable area.

The following diagram may help you to visualise this better:


NOTE: You can never write to the File Bundle (program) directory.

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.

To start with, you should understand what is meant when we talk


of the working_directory. This is a synonym for the two possible
save locations (as illustrated by the diagram above) and when
you use that directory it will do one of two things depending on
whether you are reading or writing, and whether the file you are
reading from has been changed or not:

Reading Operations - working_directory will first check the save


area to see if the file being accessed is there, and if it is uses that.
However if the file does not exists in the save area, it then checks
the file bundle area and uses that (if the file being looked for is an
included file with your game).

Writing Operations - This can only happen in the save area.


NOTE: in general GameMaker will handle all this for you and
you rarely need to use the working_directory built in variable.

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):

directory_create() (and the other directory functions) will only


work in the save area.

the file system functions will return information on files


from both the bundle and the save area, but will only write to
the save area.
the functions for writing text, binary or INI files will create a new
file in the save area if one does not already exist, copying over
any information from the original files included with the game
bundle should they exist. Note that the original files will still
remain in the read-only part of the save directory, but they won't
be referenced as long as a version exists in the read/write section
of the save area.

On the Windows, macOS and Ubuntu (Linux) platforms there are


two ways to save and load files from outside of the sandbox and
that is either using the
functions get_open_filename() and get_save_filename() (both of
these functions will require that the user select an area for
loading and saving and the return string can then be used in the
rest of the file functions to bypass the sandbox - see the function
descriptions in the language section of the manual for more
details). The other way is to disable the sandbox altogether from
the Game Options for the target platform (only available for
Desktop targets, as discussed further up this page).

On HTML5 it is also possible to load files from outside the sandbox


from a server, however this should only be done using the
function buffer_load_async() as loading synchronously has been
deprecated on most browsers and will eventually be obsoleted.
This means that files being loaded in this way should be saved as
binary files - for example, you can save an *.ini as a string
(see ini_close() for details) and then write that into a buffer
which can then be saved and loaded using the async functions.
Note that if you are loading images using sprite_add() then
these are already dealt with asynchronously.

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).

HTML5, GX.games: Everything is done through the local storage.

macOS: Storage will depend on whether the application is


sandboxed or not (following Apple's rules, with the path usually
being ~/Library/Application Support/<Game Name>).

Ubuntu (Linux): Files are stored in


the Home/.config/gamename where "Home" is the users home
directory - /home/<username>

iOS / tvOS: Storage is the standard location (as viewed through


iTunes).

Android: Files are in the standard location (which is invisible


unless the device is rooted) /data/<package name>.

It is worth noting that the HTML5 target module has a limit on


local storage (which can be between 1MB and 5MB depending on
the browser) meaning that you will not be permitted to save large
sprites, screenshots etc...

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.

List of Game File Extensions and Associated File Formats


Following is a list of common Game file formats along with their file extensions.
BIN File Format - PSX PlayStation BIOS Image
PAR File Format - FMS Aircraft Parameters File
META File Format - Exient Metadata File
N64 File Format - Nintendo 64 ROM File
NSP File Format - Nintendo Submission Package
NES File Format - Nintendo Entertainment System ROM File
SCWORLD File Format - Survivalcraft World File
DDT File Format - Football Manager Game Data File
P3T File Format - PlayStation 3 Theme File
TXD File Format - Game Texture Dictionary
EPK File Format - Eaglercraft Asset Package

W3X File Format - Warcraft 3 Expansion Map File


MCSTRUCTURE File Format - Minecraft Structure File
PXP File Format - Counter-Strike PODBot File

MCPACK File Format - Minecraft Bedrock Edition Add-On


TTR File Format - TETR.IO Replay
VRCW File Format - VRChat World
BIN File Format - Sega Genesis Game ROM
Unity3D File Format - Unity Web Player Archive
LANG File Format - Minecraft Language Localization File
LITEMOD File Format - Minecraft LiteLoader Mod File
GCF File - Nadeo Game GCF Format
OSU File - Osu! Script File Format
USX File - Unreal Static Meshes File
VPK File - Unreal Static Meshes File
MII File - Wii Virtual Avatar File Format
MCA - Minecraft Anvil Region File Format
MCR - Minecraft Region File Format
BO2 - Minecraft BO2 Object File Format
GBX File - Nadeo Game File Format
NPA File - Steins;Gate Archive File Format
SIMS3PACK File - The Sims 3 Package File
XS File - Age of Empires 3 Map AI Generator File Format
PUP File Format - PlayStation 3 Update File
SFAR - Mass Effect 3 DLC File
CLIP - Grand Theft Auto 5 Clip File
CON File- Battlefield 1942 Configuration File Format
CSD File Format - Steam Game Data Backup File
CT - Cheat Engine Cheat Table File
BMZ - Portal Bonus Map ZIP File
BNS - Portal Bonus Map Script File
PAK File Format- Video Game Package File
REP - Grand Theft Auto Replay File
RPX - Wii U Game File
SFAR - Mass Effect 3 DLC File
U8 - Mario Kit Wii Archive File
UMX - Unreal Music Package File
DEK - Magic: The Gathering Deck File
FOMOD - Fallout Mod Archive File
GAM - Saved Game File
KODU - Microsoft Kodu Game File
MGX - Age of Empires 2 Expansion Replay
OSB File - Osu! Storyboard File Format
OSK File - osu Skin File Format
OSR File - osu! Replay File Format
OSZ File - osu! Beatmap File Format
PCC - Mass Effect Package File
PSS - PlayStation 2 Game Video File
PWF - Counter-Strike PODBot Waypoint File
REL - Relocatable Module File
SAV - Nintendo DS Save File
W3N - Warcraft 3 Expansion Campaign Map File
MCWORLD - Minecraft World Backup File

The game loop


The game loop is the primary mechanism that moves the game
forward in time. Before we learn how to create this important
component, let's briefly take a look at the structure of most games.
The game structure
There are three phases to most games: the initialization phase, the
game loop, and the shutdown phase. The core of any game is the
game loop.

The game loop is a sequence of processes that run continuously as


long as the game is running. The three main processes that occur in
the game loop are input, update, and render.
The input process is how the player controls the game. This could be
any combination of keyboard, mouse, or control ...

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.

Interview with a CPU


Eventually, programmers realized having to drop off a batch of code at the computing
office and come back a few hours later for the results was a terribly slow way to get
the bugs out of a program. They wanted immediate feedback.Interactive programs
were born. Some of the first interactive programs were games:

YOU ARE STANDING AT THE END OF A ROAD BEFORE A SMALL BRICK


BUILDING . AROUND YOU IS A FOREST. A SMALL
STREAM FLOWS OUT OF THE BUILDING AND DOWN A GULLY.

> GO IN
YOU ARE INSIDE A BUILDING, A WELL HOUSE FOR A LARGE SPRING.

This is Colossal Cave Adventure, the first adventure game.

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.

A world out of time


If this loop isn’t blocking on input, that leads to the obvious question: how fastdoes it
spin? Each turn through the game loop advances the state of the game by some
amount. From the perspective of an inhabitant of the game world, the hand of their
clock has ticked forward.

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.

Seconds per second


In early video games, that second factor was fixed. If you wrote a game for the NES or
Apple IIe, you knew exactly what CPU your game was running on and you could (and
did) code specifically for that. All you had to worry about was how much work you did
each 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.

You may need to coordinate with the platform’s event loop


If you’re building your game on top of an OS or platform that has a graphic UI and an
event loop built in, then you have two application loops in play. They’ll need to play
nice together.

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.

Run, run as fast as you can


We’ve already seen the simplest possible game loop:

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.

Take a little nap


The first variation we’ll look at adds a simple fix. Say you want your game to run at 60
FPS. That gives you about 16 milliseconds per frame. As long as you can reliably do all
of your game processing and rendering in less than that time, you can run at a steady
frame rate. All you do is process the frame and then wait until it’s time for the next
one, like so:

The code looks a bit like this:

1000 ms / FPS = ms per frame.


while (true)
{
double start = getCurrentTime();
processInput();
update();
render();

sleep(start + MS_PER_FRAME - getCurrentTime());


}

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.

One small step, one giant step


Let’s try something a bit more sophisticated. The problem we have basically boils down
to:

1. Each update advances game time by a certain amount.


2. It takes a certain amount of real time to process that.

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:

double lastTime = getCurrentTime();


while (true)
{
double current = getCurrentTime();
double elapsed = current - lastTime;
processInput();
update(elapsed);
render();
lastTime = current;
}

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:

 The game plays at a consistent rate on different hardware.


 Players with faster machines are rewarded with smoother gameplay.

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.

Computers are naturally deterministic; they follow programs mechanically. Non-


determinism appears when the messy real world creeps in. For example, networking,
the system clock, and thread scheduling all rely on bits of the external world outside of
the program’s control.

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:

double previous = getCurrentTime();


double lag = 0.0;
while (true)
{
double current = getCurrentTime();
double elapsed = current - previous;
previous = current;
lag += elapsed;

processInput();

while (lag >= MS_PER_UPDATE)


{
update();
lag -= MS_PER_UPDATE;
}

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.

Stuck in the middle


There’s one issue we’re left with, and that’s residual lag. We update the game at a
fixed time step, but we render at arbitrary points in time. This means that from the
user’s perspective, the game will often display at a point in time between two updates.

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.

When we go to render, we’ll pass that in:

render(lag / MS_PER_UPDATE);

We divide by MS_PER_UPDATE here to normalize the value. The value passed


torender() will vary from 0 (right at the previous frame) to just under 1.0 (right at the
next frame), regardless of the update time step. This way, the renderer doesn’t have to
worry about the frame rate. It just deals in values from 0 to 1.
The renderer knows each game object and its current velocity. Say that bullet is 20
pixels from the left side of the screen and is moving right 400 pixels per frame. If we
are halfway between frames, then we’ll end up passing 0.5 to render(). So it draws
the bullet half a frame ahead, at 220 pixels. Ta-da, smooth motion.

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.

So the extrapolation is a bit of a guess and sometimes ends up wrong. Fortunately,


though, those kinds of corrections usually aren’t noticeable. At least, they’re less
noticeable than the stuttering you get if you don’t extrapolate at all.

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:

Do you own the game loop, or does the platform?


This is less a choice you make and more one that’s made for you. If you’re making a
game that runs in a web browser, you pretty much can’t write your own classic game
loop. The browser’s event-based nature precludes it. Likewise, if you’re using an
existing game engine, you will probably rely on its game loop instead of rolling your
own.

 Use the platform’s event loop:


o It’s simple. You don’t have to worry about writing and optimizing the core loop of the
game.
o It plays nice with the platform. You don’t have to worry about explicitly giving the host
time to process its own events, caching events, or otherwise managing the impedance
mismatch between the platform’s input model and yours.
o You lose control over timing. The platform will call your code as it sees fit. If that’s not
as frequently or as smoothly as you’d like, too bad. Worse, most application event loops
weren’t designed with games in mind and usually are slow and choppy.
 Use a game engine’s loop:
o You don’t have to write it. Writing a game loop can get pretty tricky. Since that core
code gets executed every frame, minor bugs or performance problems can have a large
impact on your game. A tight game loop is one reason to consider using an existing
engine.
o You don’t get to write it. Of course, the flip side to that coin is the loss of control if
you do have needs that aren’t a perfect fit for the engine.
 Write it yourself:
o Total control. You can do whatever you want with it. You can design it specifically for
the needs of your game.
o You have to interface with the platform. Application frameworks and operating systems
usually expect to have a slice of time to process events and do other work. If you own
your app’s core loop, it won’t get any. You’ll have to explicitly hand off control
periodically to make sure the framework doesn’t hang or get confused.

How do you manage power consumption?


This wasn’t an issue five years ago. Games ran on things plugged into walls or on
dedicated handheld devices. But with the advent of smartphones, laptops, and mobile
gaming, the odds are good that you do care about this now. A game that runs
beautifully but turns players’ phones into space heaters before running out of juice
thirty minutes later is not a game that makes people happy.

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.

 Run as fast as it can:

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.

 Clamp the frame rate:

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.

How do you control gameplay speed?


A game loop has two key pieces: non-blocking user input and adapting to the passage
of time. Input is straightforward. The magic is in how you deal with time. There are
a near-infinite number of platforms that games can run on, and any single game may
run on quite a few. How it accommodates that variation is key.

 Fixed time step with no synchronization:

This was our first sample code. You just run the game loop as fast as you can.

o It’s simple. This is its main (well, only) virtue.


o Game speed is directly affected by hardware and game complexity. And its main vice is
that if there’s any variation, it will directly affect the game speed. It’s the fixie of game
loops.
 Fixed time step with synchronization:
The next step up on the complexity ladder is running the game at a fixed time step but
adding a delay or synchronization point at the end of the loop to keep the game from
running too fast.

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.

You might also like