<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by that games guy on Medium]]></title>
        <description><![CDATA[Stories by that games guy on Medium]]></description>
        <link>https://medium.com/@thatgamesguy?source=rss-766830793bc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DZfokaDQoju5DtFQ6bH4GA.png</url>
            <title>Stories by that games guy on Medium</title>
            <link>https://medium.com/@thatgamesguy?source=rss-766830793bc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 21:54:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thatgamesguy/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[That Adventure Game 2: First Draw]]></title>
            <link>https://medium.com/game-dev-series/game-dev-2-first-draw-2d067153950c?source=rss-766830793bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d067153950c</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[vikings]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[resource-management]]></category>
            <dc:creator><![CDATA[that games guy]]></dc:creator>
            <pubDate>Wed, 09 Feb 2022 07:02:55 GMT</pubDate>
            <atom:updated>2022-02-10T10:52:10.324Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*_HO4iriVVpOQZGdmoHFBIg.png" /><figcaption>Our first character in the game</figcaption></figure><h4>Introducing the Viking</h4><blockquote>This is part of an ongoing series where we write a complete 2D adventure game in C++ and SFML. Starting from the basics (game loops, rendering etc.), we’ll quickly move on to more advanced topics, such as handling collisions, Quadtrees, animations, ray tracing, and creating component-based objects. In the process, we’ll cover everything you need to create 2D games. You can download the source code from the projects <a href="https://github.com/thatgamesguy/that_game_engine">GitHub page</a>. If you haven’t read it yet, it’s worth starting with the <a href="https://medium.com/@thatgamesguy/game-dev-0-introduction-3723bae0fa8f">first tutorial in the series</a>, as we’ll be building on the concepts presented there.</blockquote><p>In this tutorial, we will load an image from a file and draw it on the screen. We will also briefly discuss platform-dependent code, as MacOS wants to do things a bit differently, and we want to ensure the experience is the same on every platform.</p><h3>Working Directory</h3><p>Before we can draw anything in our game, we need to load the resource (in this case the image) from disk; and before we can load the resource we need to be able to locate it. Fortunately for us, SFML automatically looks in the resource folder on Windows and Linux, and with a bit of extra code, on MacOS as well. SFML helps to minimise the amount of platform-specific code that we’ll have to write, however there are some occasions when that will still prove necessary.</p><p>As a side-note, I have not been able to test a Linux build. I have been informed and believe the code will be able to locate the image on Linux, but if you experience any problems, let me know in the comments and I’ll look into it. Eventually I’ll get round to testing it on Linux, and if any changes need to be made I’ll update this tutorial.</p><p>When we load a resource, we want to be able to call a function that returns a string to what I refer to as the working directory. This is the directory that will contain our resources. We want to be able to locate our resources regardless of the OS the game is installed on. In our game we want to be able to do something like this:</p><pre>const std::string fileName = “viking.png&quot;; <br>const std::string filePath = workingDir.Get() + fileName;</pre><p>Where workingDir.Get() will return a string to the games resource folder and “viking” is the name of our image. This abstracts away how we create the path to the file and if we need to make any changes to that process, we will only need to change the “WorkingDirectory” class (which we will be creating shortly).</p><p>To ensure that the code we write can find your resources, make sure you place any files in your IDEs ‘Resources’ folder.</p><h3>Implementation</h3><p>Create a new header and implementation file for a <strong>WorkingDirectory </strong>class. The numbered comments are explained in detail after the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f853465317e773530c3f0f6d87376eca/href">https://medium.com/media/f853465317e773530c3f0f6d87376eca/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b5668799d2d22797a9e9668c5035ecb/href">https://medium.com/media/1b5668799d2d22797a9e9668c5035ecb/href</a></iframe><p><strong>Comment #1:</strong> As you can see the <strong>Get</strong> method is straightforward, it simply returns a reference to the string “./” (initialised in the constructor), which points to the current directory. The string can also be empty i.e. “” and it will still work. So why do we need code to get the working directory if it just returns the equivalent of an empty string? Because as with many things we write at the moment, this lays the foundations for changes we will be making in future; for example: we may want the absolute paths to resources, and we can also create modifiers that return specific folders for different resources.</p><p>A quick note on the functions <em>inline</em> declaration, if you haven’t seen this keyword before: it simply means that whenever this function is called, replace the call with a copy of the functions body. This is performed at compile-time and is used to reduce the overhead of calling a method. It’s generally used for smaller, simple methods that are used frequently; such as our Get method. You can read more about inline methods <a href="https://www.tutorialspoint.com/cplusplus/cpp_inline_functions.htm">here</a>.</p><p><strong>Comment #2: </strong>The code gets a bit more complicated when we look at the constructor of WorkingDirectory. It is surrounded by a <a href="http://www.cplusplus.com/doc/tutorial/preprocessor/">preprocessor directive</a>: “#ifdef MACOS”. This ensures it runs only when the compiler flag “MACOS” is used; in fact the code is removed from the compilation when the compiler flag is absent. We would only include this compiler flag if we’re building for MacOS.</p><p>The code within the preprocessor directive sets the working directory to that of the source folder (the same folder your source and resource files are located). This only needs to be performed once, so currently we need to ensure that WorkingDirectory is being instantiated at least once. Without these lines the MacOS build would not find any resources that you’ve placed in the resource folder.</p><p>If you are compiling your code within Xcode, you can add a compiler flag by following these steps:</p><ol><li>Click on the game engine project in the sidebar.</li><li>Click on Build Settings on the top row.</li><li>In the search bar type “custom compiler flag”.</li><li>In “Other C Flags” enter “-D MACOS”. The Other C++ Flags field will be automatically populated.</li></ol><p>You’ll end up with a screen that looks similar to the one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*303pX66g7gcH5MMnmpauqg.png" /></figure><p>On MacOS, you will also need to link to the CoreFoundation framework (last step I promise) for our custom code to work:</p><ol><li>You can do this on the General tab; you’ll find a section called ‘Linked Frameworks and Libraries’.</li><li>Click on the plus sign.</li><li>Locate CoreFroundation.framework.</li><li>Click Add.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*FALbcDQFyMyPJwXSNFgRdg.png" /></figure><p>We now have a method of accessing the resource directory on each platform, lets make use of it in our <strong>Game</strong> class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21c8fb89b5fb1b209e2637af200f14bd/href">https://medium.com/media/21c8fb89b5fb1b209e2637af200f14bd/href</a></iframe><p>I chose a viking sprite, available from <a href="https://opengameart.org/content/viking-shieldmaiden-animated">here</a>, to test our resource loading. Place the sprite within your projects resource folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fe75360f22b04b2b8a5306ecf9efe26/href">https://medium.com/media/6fe75360f22b04b2b8a5306ecf9efe26/href</a></iframe><p>If you are unsure about the difference between a <a href="https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1Texture.php">sf::Texture</a> and a <a href="https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1Sprite.php">sf::Sprite</a>, don’t worry too much. They will be explained in more detail when we create our resource management system. For now, it is enough to know that a sf::Texture is a heavyweight object and we do not want to create them unnecessarily, and sf::Sprite stores a reference to a texture and allows us to draw all or a part of the texture.</p><p>With the references created we can load the image in the <strong>Game</strong> class constructor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a30711fce8115a513c37dff0cd596a0b/href">https://medium.com/media/a30711fce8115a513c37dff0cd596a0b/href</a></iframe><p><strong>Comment #1: </strong>This is where we use our newly created WorkingDirectory. Note that “viking.png” should be changed to match the name of your file.</p><p>If you run the project now, you won’t see anything other than the white screen that we saw in the previous tutorial. This is because we are not yet drawing the sprite. We’ll do that in the Draw method (as you may have guessed).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a04d5b2e50fe62a48f4004114c3cb6a4/href">https://medium.com/media/a04d5b2e50fe62a48f4004114c3cb6a4/href</a></iframe><p>All of our draw calls will be sandwiched between the begin and end draw methods.</p><p>When you run the game you will now see the sprite drawn to the screen. Drawing textures to the window is a significant step forwards for our fledgling adventure game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*xNM_yMF2ppvdAjosFz_Sjg.png" /></figure><p>In the next tutorial, we will look at moving the viking around the window at a constant speed, independent of the frame rate.</p><p>Thank you for reading 🙂</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*4blJT7Ei8NX4ZBOJCw_D7w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d067153950c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/game-dev-series/game-dev-2-first-draw-2d067153950c">That Adventure Game 2: First Draw</a> was originally published in <a href="https://medium.com/game-dev-series">That Adventure Game</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[That Adventure Game 0: Introduction]]></title>
            <link>https://medium.com/game-dev-series/game-dev-0-introduction-3723bae0fa8f?source=rss-766830793bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/3723bae0fa8f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[sfml]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[that games guy]]></dc:creator>
            <pubDate>Tue, 08 Feb 2022 15:17:49 GMT</pubDate>
            <atom:updated>2022-02-10T10:40:02.701Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ZgSTCMqyro67EbPNgoDWOg.gif" /><figcaption>Sneak peek at the current state of the game</figcaption></figure><h4>Defining the framework we will use for our game.</h4><blockquote>This is part of an ongoing series where we write a complete 2D adventure game in C++ and SFML. Starting from the basics (game loops, rendering etc.), we’ll quickly move on to more advanced topics, such as handling collisions, Quadtrees, animations, ray tracing, and creating component-based objects. In the process, we’ll cover everything you need to create 2D games. You can download the source code from the projects <a href="https://github.com/thatgamesguy/that_game_engine">GitHub page</a>.</blockquote><p>This is the first of a number of tutorials that will guide you through the development of a complete, full-featured adventure game. Along the way, I’ll discuss a number of useful patterns and systems; and by the end of the series, you will have a complete game. By following the tutorials, you will not only have a better understanding of how games are built, but you will have the foundational knowledge to create your own games, no matter the genre.</p><p>A sneak peek of a some of the things we’ll create in this series:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J8J_nLOw7aeIzG6kvFVq2Q.png" /><figcaption>Quadtree in action</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*02KZqfmYIhnGi-KEQZY5ow.png" /><figcaption>One of the exterior maps</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*sOZu7HkuYFZ54jKxIroPpw.gif" /><figcaption>Bow and Arrow animation playing using our animation system</figcaption></figure><p>New tutorial will be released regularly extending our game. Some of the features we’ll implement include, how to:</p><ul><li>Get input from the players: polling and real-time; and when to use each.</li><li>Manage the various resources a typical game requires (textures, audio, and font files to name a few).</li><li>Manage different scenes e.g. main menu, game, and pause states.</li><li>Animate our characters.</li><li>Create a simple physics engine.</li><li>Create and import tile maps.</li><li>Efficiently managing collisions with the map and with other objects in the level.</li><li>Create an entity component system.</li><li>Create an audio engine.</li><li>Manage inter-system communication.</li><li>Create and handle events.</li><li>Serialise and de-serialise objects.</li></ul><p>Creating games is a multi-faceted and at times complicated subject, and this is only a small selection of what we will cover. This tutorial series is aimed at existing programmers that want to become game developers (or who at least have some interest in the field).</p><p>For this project we will use C++ and SFML. I assume you have some knowledge of C++ or a similar language and will deep dive into language-specific feature. If you are not comfortable with C++, I would recommend first following an intro course. I do not assume any knowledge of SFML and I’ll discuss relevant SFML topics as they arise.</p><h3>Why use SFML?</h3><p>SFML is well documented online so I won’t go into details about what exactly it is, other than that it will help us with various functions such as drawing to the screen, and playing audio. I recommend starting at SFML’s website for more information: <a href="https://www.sfml-dev.org.i/">https://www.sfml-dev.org</a>. I will however mention the reasons why I am using it for this tutorial series:</p><ul><li>I have used it before so I can focus on the actual implementation without learning a new library.</li><li>It has a number of bindings for different languages, including: java, python, and ruby. I’ll be using the C++ bindings but you are free to use any of the other available languages.</li><li>It has a decent install base; which means finding support should not be too difficult.</li><li>It is multi-platform, you can follow along on Windows, MacOS, or Linux. It is also being ported to Android and iOS, but that was not available when I started this series.</li></ul><p>SFML is of course not the only choice and you can find a number of good alternatives online.</p><p>Having said all that, it is not really important what library you choose to use. If you are more comfortable with using a different library or even language then feel free to do so. It does not matter what language the game is programmed in, what is important is how we build and combine the various systems (or building blocks) of our game.</p><h3>Why not use Unity/Unreal Engine?</h3><p>I’m a big fan of Unity, having used it for most of my professional career. I’m sure Unreal Engine is great too, I just happened to use Unity (in fact I’ve even <a href="https://www.packtpub.com/product/unity-2020-by-example-third-edition/9781800203389">written a beginners Unity book</a> that you should totally check out). However, I also think that as a games programmer, you should have a good idea what is going on under the proverbial hood. So while I’m very thankful that I no longer have to write my own Entity Component Systems and Animation systems, I like to understand how they work from first(ish) principles.</p><h3>How do you Setup SFML?</h3><p>This is <a href="https://www.sfml-dev.org/tutorials/2.5/">well documented online</a> and I will not go into detail here, as the process will surely change at some point.</p><p>I create and test the projects in Visual c++ 14 (2015) 32bit for Windows and Clang 64bit for MacOS. You can download them from the SFML site, but again you are free to use whichever implementation you would like. I will host the source files for each tutorial, once you have a project setup you can drag and drop these files into your project.</p><p>You can download the source code for each chapter from the Github repo as they become available (link will be at the top of each page). I will include the source files for each chapter in the separate folders and a current build for Xcode. The Xcode build can be considered the Dev build, it may not always run and will include code that has not yet been covered in the series.</p><p>This is the first and most likely last post of the series that does not include any code. From now on, we’ll be getting stuck in and creating new features for our game. If you have any issues with setup or have suggestions on anything you would like to see included, then please let me know in the comments.</p><p>Thank you for reading 🙂</p><p><strong>Update</strong>: <a href="https://medium.com/@thatgamesguy/game-dev-1-creating-the-game-loop-6ddaed32536c">the next tutorial in the series is now live</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*4blJT7Ei8NX4ZBOJCw_D7w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3723bae0fa8f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/game-dev-series/game-dev-0-introduction-3723bae0fa8f">That Adventure Game 0: Introduction</a> was originally published in <a href="https://medium.com/game-dev-series">That Adventure Game</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[That Adventure Game 1: Creating the Game Loop]]></title>
            <link>https://medium.com/game-dev-series/game-dev-1-creating-the-game-loop-6ddaed32536c?source=rss-766830793bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ddaed32536c</guid>
            <category><![CDATA[games]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rendering]]></category>
            <dc:creator><![CDATA[that games guy]]></dc:creator>
            <pubDate>Tue, 08 Feb 2022 12:18:08 GMT</pubDate>
            <atom:updated>2022-02-10T10:50:23.969Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*-mKk-dqD1B8gThDDLd2kPQ.png" /><figcaption>Sneak peak at an exterior map</figcaption></figure><h3>That Adventure Game 1: The Game Loop</h3><h4>Creating the heart of our game.</h4><blockquote>This is part of an ongoing series where we write a complete 2D adventure game in C++ and SFML. Starting from the basics (game loops, rendering etc.), we’ll quickly move on to more advanced topics, such as handling collisions, Quadtrees, animations, ray tracing, and creating component-based objects. In the process, we’ll cover everything you need to create 2D games. You can download the source code from the projects <a href="https://github.com/thatgamesguy/that_game_engine">GitHub page</a>. If you haven’t read the intro to the series, you can check it out <a href="https://medium.com/@thatgamesguy/game-dev-0-introduction-3723bae0fa8f">here</a>.</blockquote><p>In this first tutorial (not including the intro), we will create our initial game loop and our first window.</p><h3>Initial Project Setup</h3><p>You can follow the <a href="http://www.sfml-dev.org/tutorials">instructions here</a> for platform specific instructions on how to create the initial project. At the moment you can follow along on Windows, MacOS, or Linux; although mobile support has been promised. Once you have a working SFML project, make sure to delete any classes that are automatically generated for you, as we’ll write everything we need from scratch.</p><h3>The Game Loop</h3><p>The first thing we’ll be writing is our game loop. You’ll often hear the game loop referred to as the “heart of a game”. It will be responsible for calling all of our game code and keeping the game running. A game loop can become quite complicated (and we will definitely be adding to it in future) but at its core, it is simply a loop that contains a number of methods that when called perform specific actions in our game. We will perform input, physics, AI updates and drawing during each loop. Examples of methods you will find in a typical game loop include:</p><ul><li><em>Initialise/EarlyUpdate:</em> this is usually called first. You would place any initialisation code that needs to be performed before updating and drawing here.</li><li><em>Update</em>: This is where most of the game logic will go; including: movement, AI, and animation updates.</li><li><em>LateUpdate</em>: Any logic that relies on data calculated in the Update method will go here, for example: you could place collision logic here that checks for collisions once every entities position has been updated in the Update method.</li><li>FixedUpdate: A special method that is invoked a set number of times a second, hence the name ‘Fixed’. This is normally used to update physics engines that require a fixed update schedule. This will be explained in detail when we come to implement our own.</li><li><em>Draw/Render</em>: Once all the entities have been updated, we draw them to the screen. This method will be responsible for drawing everything, including the games UI.</li></ul><p>Its not uncommon for games to have less/more methods than the ones stated above; you could add specific functions for processing user input, updating physics etc. To begin with we will implement: Update, LateUpdate, and Draw functions. As time goes on we may add a ProcessInput, FixedUpdate and a PhysicsStep method to our game loop; they will be explained in more detail when we need them.</p><p>Using this pattern we can also keep track of the progress of time and use this to ensure that our game runs as intended no matter the hardware (within reason… I can confidently say that this will not run well on a Gameboy). We will discuss frame-rate/update independence, when we we look at moving our first sprite around the screen.</p><h3>Loop implementation</h3><p>We’ll start by defining how we want to call the game loop. Create a class called <strong>Main.cpp</strong> (no need to create a corresponding header file). This will be our entry point into the program. In this class, we will outline the initial loop that we would like our game to have:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f0d1e510c48d6bf7409253b16fe4203/href">https://medium.com/media/1f0d1e510c48d6bf7409253b16fe4203/href</a></iframe><p>While this won’t build (as we haven’t created the game class), it does outline the minimum we want from our game loop. And it is just that, the minimum we require; there are a number of changes we will make to how the game loop functions in a future tutorial but for now this is all we need.</p><p>Create a <strong>Game</strong> class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89f82f4069a1bde1e461ec44c645707a/href">https://medium.com/media/89f82f4069a1bde1e461ec44c645707a/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a52741dc0d015f1955048c4b2884d3cc/href">https://medium.com/media/a52741dc0d015f1955048c4b2884d3cc/href</a></iframe><p>Our project should now build and we have our basic game engine loop setup. While it isn’t doing anything yet, that will change shortly.</p><h3>Creating a Window Class</h3><p>Now we have our game loop, lets lay the ground work for drawing and updating a sprite (which we’ll cover in the next tutorial). To help us with that SFML provides something called a <a href="https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1RenderWindow.php">sf::RenderWindow</a>. SFML defines a RenderWindow as a “<a href="https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1Window.php">Window</a> that can serve as a target for 2D drawing”. So with that in mind we know that a RenderWindow can do everything that an SFML window can, plus it adds 2D drawing features that will come in very handy shortly. Initialising a RenderWindow will create and display a window in your chosen OS that we can then place our sprites on; which is exactly what we need!</p><p>We’ll wrap this RenderWindow in our own class, so we can extend its functionality in future. Create a <strong>Window</strong> class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/097c6d0fe80c39284607ff9e5ee349b3/href">https://medium.com/media/097c6d0fe80c39284607ff9e5ee349b3/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b3543b556b60915b6b0ef1cd50f67f8/href">https://medium.com/media/8b3543b556b60915b6b0ef1cd50f67f8/href</a></iframe><p>You’ll notice numbered comments in the code above, I will use these whenever I want to discuss a line in more detail. The numbered points below explain the line(s) at the numbered comments in the code above</p><p><strong>1.</strong> The RenderWindow constructor accepts a <a href="https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1VideoMode.php">sf::VideoMode</a> as a parameter. The VideoMode can be use to define the width, height, and depth of the window. We are currently creating a non-fullscreen window with a resolution of 800 x 600 pixels, although this will change later as we’ll eventually want to make the window full-screen and user adjustable. RenderWindow also accepts a sf::Style parameter; which is an enum and includes options for showing the title bar (an option we are currently using), resizing the window, and whether the window starts fullscreen.</p><p><strong>2.</strong> Vertical Sync, often referred to as Vsync, allows a player to sync the frame rate of the game to the refresh rate of the monitor. It does this by reducing the frame rate, as unfortunately it cannot increase the frame rate. Consequently there will be a dip in the frame-rate with this setting turned on (unless your frame-rate happened to already sync with the monitor, unlikely but not impossible). Whilst it has its drawbacks, Vsync should help reduce visual artefacts caused by the graphics card rendering individual frames faster that a monitor can draw them, resulting in weird graphical glitches. So its a trade off between a games FPS (frames per second) and possible graphical errors. Eventually we will want this setting to be able to be changed by the player (you’ll often see a Vsync setting in many modern games) but for now we’ll leave it hard-coded.</p><p><strong>3. </strong>In the Windows update method we listen for a close event and if received we close the window. This allows the player to quit the game with cmd-q on Mac and alt-f4 on Windows and Linux. You may be wondering why this is required; surely when the player attempts to close the window, we’d want the window to actually close? But that is not always the case, in fact in future we will want to do a number of things before closing the window; for example: we could show the player an ‘Are you sure you want to quit?’ option or we could save the players current progress. We will be writing our own event system in future so I will go into much more detail on the topic but for now it’ll be good to know a couple of SFML event specifics:</p><ul><li><a href="https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1Event.php#details">sf::Event</a> class is a union so only one of its members is valid at one time. As all members share the same memory space,<strong> </strong>we need to test the event type to make sure we do not attempt to access invalid memory.</li><li>pollEvent returns true if an event has occurred and fills the event with the relevant data (as the event object is passed by reference).</li></ul><p>We will only rely on this event system for specific window events. All other game events will be handled by our own event system that we will write in a future tutorial.</p><p><strong>4. </strong>Many graphics packages require the user to call a begin and end draw method before and after drawing; and SFML is no different. The BeginDraw method clears the screen to a uniform colour, without this call you’ll see all previously drawn frames; and the EndDraw method is responsible for displaying the items we have requested to draw.</p><h3>Updating Game Class</h3><p>Update the game class to take advantage of our new window class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fee47c7815c71a2aa33e75fa19cd2cda/href">https://medium.com/media/fee47c7815c71a2aa33e75fa19cd2cda/href</a></iframe><p>Initialise and update the window in Game.cpp:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdb1f20428547e25c684582442a71e83/href">https://medium.com/media/bdb1f20428547e25c684582442a71e83/href</a></iframe><p>We should really allow any future players of our game to quit, to do that we will use the window to decide whether the game is running:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6cbcf91bacde3f2f061bebae0761cd12/href">https://medium.com/media/6cbcf91bacde3f2f061bebae0761cd12/href</a></iframe><p>Now, when the project is run you’ll be greeted with a window! It may currently only be a white-filled screen but its a start.</p><p>If you’ve got this far then congratulations! We have begun to lay a solid groundwork for our game, which we will extend in future tutorials. If you have any questions or suggestions then please let me know in the comments.</p><p>Thank you for reading 🙂</p><p><strong>Update</strong>: <a href="https://medium.com/@thatgamesguy/game-dev-2-first-draw-2d067153950c">the next tutorial in the series is now live</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*4blJT7Ei8NX4ZBOJCw_D7w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ddaed32536c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/game-dev-series/game-dev-1-creating-the-game-loop-6ddaed32536c">That Adventure Game 1: Creating the Game Loop</a> was originally published in <a href="https://medium.com/game-dev-series">That Adventure Game</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[That Adventure Game 10: Object Collection]]></title>
            <link>https://medium.com/game-dev-series/that-adventure-game-10-object-collection-511cba8615c9?source=rss-766830793bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/511cba8615c9</guid>
            <category><![CDATA[sfml]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[that games guy]]></dc:creator>
            <pubDate>Mon, 18 Jun 2018 15:00:26 GMT</pubDate>
            <atom:updated>2022-03-27T07:03:06.919Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*65J8l5R561k1eaLmcaPF-w.gif" /><figcaption>Sneak peak at a (somewhat broken) bow and arrow animation</figcaption></figure><h4>Write a collection to store game objects in our Adventure Game.</h4><blockquote>This is part of an ongoing series where we write a complete 2D adventure game in C++ and SFML. Starting from the basics (game loops, rendering etc.), we’ll quickly move on to more advanced topics, such as handling collisions, Quadtrees, animations, ray tracing, and creating component-based objects. In the process, we’ll cover everything you need to create 2D games. You can download the source code from the projects <a href="https://github.com/thatgamesguy/that_game_engine">GitHub page</a>. If you haven’t read the intro to the series, you can check it out <a href="https://medium.com/@thatgamesguy/game-dev-0-introduction-3723bae0fa8f">here</a>.</blockquote><p>When we created our component system, we wrote Awake and Start methods for our objects. However, they are not yet being called anywhere. We need to fix this before the next tutorial where we will begin our animation system. Also, we are currently responsible for maintaining, updating, and drawing our objects ourselves. We only have one object at the moment so it’s not really a problem, but we do not want to have to manually call update and draw functions when we have 100+ objects. Therefore, as well as calling the Awake and Start functions, we will also create a structure to store our objects, the ObjectCollection.</p><p>There’s no background information required to understand the concepts in this tutorial, so let’s get coding straight away by creating our <strong>ObjectCollection</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f21999074a42d4ebc70e9c6244f109ca/href">https://medium.com/media/f21999074a42d4ebc70e9c6244f109ca/href</a></iframe><p><strong>Comment #1</strong>: we separate the processing of new objects into its own method so it can be run at a convenient time (normally the beginning or end of a frame). This method will be responsible for moving objects added that frame from a temporary new object collection to the main object collection so they are updated, drawn etc.</p><p><strong>Comment #2</strong>: this is used to temporarily store recently added objects so that we can choose when they are added to the game by invoking ProcessNewObjects. This will become clearer shortly when we write the method.</p><p>The Update, LateUpdate, and Draw methods will loop through all objects contained in the objects collection and call the methods of the same name on the objects:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e744a79d46391e351e230b5b0de94e47/href">https://medium.com/media/e744a79d46391e351e230b5b0de94e47/href</a></iframe><p>When we add an object we insert it into a new objects list. This list is processed by the ProcessNewObjects function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e5333f8a42b4a4252637a5ca97f3441/href">https://medium.com/media/3e5333f8a42b4a4252637a5ca97f3441/href</a></iframe><p>ProcessNewObjects will be called at the beginning of the frame. When we process new objects we need to call their Awake and Start methods, which resolves our first issue (the Awake and Start methods are now being called when an object is added to the game). Lastly, we copy the new objects to our objects list so we can update and draw them during the next frame.</p><p>There may come a time when we need to add an object to a number of collections, if/when that happens we will look into how we can implement that; but until then each scene will have its own object collection, which will contain unique objects for that scene. Add the ObjectCollection to our game scene class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c5d25fdfdb2bbfdb8cf37fc99ec6687/href">https://medium.com/media/5c5d25fdfdb2bbfdb8cf37fc99ec6687/href</a></iframe><p>Make sure you delete the reference to the player as we’ll be using our new object collection.</p><p>Rather than update and draw the player directly, they update/draw the object collection. Now, whenever we add an object to our collection we no longer need to manually call its update/draw methods.</p><p>Next, change the OnCreate function so that it creates a new player object and adds it to our collection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abe8df8af0d9e9d6aeea832f9c35f60d/href">https://medium.com/media/abe8df8af0d9e9d6aeea832f9c35f60d/href</a></iframe><p>If you run the game, you’ll notice that the player is not being drawn. We are adding the object to the collection but we are not calling the ProcessNewObjects function that moves the object from the new objects collection to the collection that is updated and drawn. We’ll process the new objects at the start of a new frame before we do anything else.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be6c4171144da9e9f144a59597143926/href">https://medium.com/media/be6c4171144da9e9f144a59597143926/href</a></iframe><p>Now when we run the game the Viking is back again!</p><p>We can now add objects but what happens when we want to remove an object? We will need a way to flag an object as ready for removal and then create a similar function as ProcessNewObjects but for processing removals.</p><p>Creating a removal flag can be accomplished with a simple boolean and some accessors/mutators in our Object class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13108e2736c3e943ad475ea8c912ce5d/href">https://medium.com/media/13108e2736c3e943ad475ea8c912ce5d/href</a></iframe><p>This flag will be used to determine if an object should be removed from a collection. Create a new method in ObjectCollection that will process removals.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91c213df0057c5d4acdf87cace1d26a2/href">https://medium.com/media/91c213df0057c5d4acdf87cace1d26a2/href</a></iframe><p>This loops through all of our current objects and removes it from the collection if the removal flag is set. We need to call this method in our game scene at a suitable moment. Let’s do this just before we process new objects in the Update method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b1bd5884a1ac1312448956e9b20e09b/href">https://medium.com/media/1b1bd5884a1ac1312448956e9b20e09b/href</a></iframe><p>With this implemented, if we want to remove an object from the game, it is as simple as calling the QueueForRemoval method on that object (we’ll demo this in a later tutorial). It should be noted that if any of our classes keeps its own reference to an object it will no longer be drawn or updated by the collection but because we are using smart pointers you will still be able to access the various components of the object and even manually update/draw the object if need be.</p><p>By creating a class responsible for objects we can have different collections for different scenes, which will allow us to:</p><ul><li>easily draw and update different objects depending on the scene</li><li>manage when objects are added and removed from a scene</li><li>have a centralised place for storing objects</li></ul><p>It’s also worth briefly mentioning that currently we are creating new objects and erasing them as need be. This is very rarely the best way to do this and in future tutorials, we will definitely be looking into implementing <a href="https://en.wikipedia.org/wiki/Object_pool_pattern">object pooling</a>. You can see an example of an object pool that I wrote in Unity <a href="https://github.com/thatgamesguy/unity_game_foundations">here</a>.</p><p>Thank you for reading 🙂</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*4blJT7Ei8NX4ZBOJCw_D7w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=511cba8615c9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/game-dev-series/that-adventure-game-10-object-collection-511cba8615c9">That Adventure Game 10: Object Collection</a> was originally published in <a href="https://medium.com/game-dev-series">That Adventure Game</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[That Adventure Game 9: Resource Management]]></title>
            <link>https://medium.com/game-dev-series/that-adventure-game-9-resource-management-e2ee23beab0c?source=rss-766830793bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2ee23beab0c</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[sfml]]></category>
            <category><![CDATA[resource-management]]></category>
            <dc:creator><![CDATA[that games guy]]></dc:creator>
            <pubDate>Mon, 11 Jun 2018 15:00:12 GMT</pubDate>
            <atom:updated>2022-03-20T09:03:45.124Z</atom:updated>
            <content:encoded><![CDATA[<h4>Create a resource allocator to manage our Adventure Games assets</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*mJp_-c2G3loL_8oQwVXRXg.png" /><figcaption>Resource management is not just a consideration for players of RTS games</figcaption></figure><blockquote>This is part of an ongoing series where we write a complete 2D adventure game in C++ and SFML. Starting from the basics (game loops, rendering etc.), we’ll quickly move on to more advanced topics, such as handling collisions, Quadtrees, animations, ray tracing, and creating component-based objects. In the process, we’ll cover everything you need to create 2D games. You can download the source code from the projects <a href="https://github.com/thatgamesguy/that_game_engine">GitHub page</a>. If you haven’t read the intro to the series, you can check it out <a href="https://medium.com/@thatgamesguy/game-dev-0-introduction-3723bae0fa8f">here</a>.</blockquote><p>As games become more complex, the issue of how to manage a games assets is only becoming more difficult; which is why, even though we do not have many resources at the moment, it is a good idea to start the groundwork on what will become a robust and generic (it can handle any resource we throw at it) resource management system.</p><p>In the context of this tutorial, a resource can include sprites, audio files, and fonts; but they can also be text, XML, and JSON data files. It is pretty much anything that is not code.</p><p>Our resource manager will handle instantiation, allocation, and retrieval (using a resource id) of our games assets. It will also be generic so that we can easily instantiate different resource managers that are responsible for allocating different resources.</p><p>I attempt to avoid using the word ‘manager’ in my class names (you’ve probably seen many examples of GameManagers, LevelManagers, etc.) for many of the reasons outlined <a href="https://blog.codinghorror.com/i-shall-call-it-somethingmanager/">here</a>. With that in mind, I’ll call our resource manager class <strong>ResourceAllocator</strong>. This provides a bit more information about what the class actually does.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2fb67219507b2a7db69c0739c14dd1a/href">https://medium.com/media/f2fb67219507b2a7db69c0739c14dd1a/href</a></iframe><p>The class makes use of <a href="http://www.cplusplus.com/doc/oldtutorial/templates/)">template functions</a>. As the methods are templates they will need to be created in the header file.</p><p>The Add function is responsible for loading the resource and adding it to our resource allocator.</p><p><strong>Comment #1:</strong> we store the file path as well as the resource so we can use it as a unique identifier. Two assets with the same file path are assumed to be the same asset. This prevents us from creating the same assets twice.</p><p><strong>Comment #2</strong>: as we call LoadFromFile on our new resource, it is important that any asset we use has this method implemented. SFML resources (sf::Texture, sf::Font etc.) have this method by default so we do not need to worry about writing our own implementation for them.</p><p>The Add method is relatively simple. It provides the bare bones of what we require from a resource manager. We will change things in future tutorials but for now, it works and does everything we need it to. It is worth noting that it returns an integer, this is the id of the resource. If we want to retrieve or remove a resource we will need this id.</p><p>Now that we can add resources, let’s create the Remove method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e44759829f7bb363f882af8a64e5d3bb/href">https://medium.com/media/e44759829f7bb363f882af8a64e5d3bb/href</a></iframe><p>This iterates over our resource collection and if it finds the resource with the associated id it is removed from the collection.</p><p>Adding and removing won’t do us any good if we cannot retrieve our resources. For that we’ll create a Get method. We will also create a method to check if an allocator has a resource with a specified id.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35cbe7822963d2d556d9f020ace66a0a/href">https://medium.com/media/35cbe7822963d2d556d9f020ace66a0a/href</a></iframe><p>A <a href="http://en.cppreference.com/w/cpp/memory/shared_ptr">shared_ptr</a> is returned to a resource (if present).</p><p>With the resource allocator complete for now, we can change our existing code base to make use of it, starting with the sprite component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/823b81cdadfe824d7ac538fc511a19d4/href">https://medium.com/media/823b81cdadfe824d7ac538fc511a19d4/href</a></iframe><p><strong>Comment #1:</strong> we currently need to manually pass the reference to the resource allocator to the component; in future, we can look at different ways of accomplishing this.</p><p>Make sure you delete the existing reference to the texture as we will retrieve this from our new resource allocator. We’ll keep the reference to the sprite as this is a lightweight structure. You can find out more about SFML sprites and textures <a href="https://www.sfml-dev.org/tutorials/2.5/graphics-sprite.php">here</a>.</p><p>We now set our sprites texture by retrieving a smart pointer to a texture from our resource allocator. As the texture is on the stack the local reference is removed at the end of the function. Each sprite component no longer needs to store their own texture as our resource allocator handles that for us. This prevents us from allocating duplicate textures as we create more sprite components.</p><p>Now that our sprite component requires a texture allocator, any class that instantiates the component will need to inject that object. Therefore our game and splash screen scene will need to either create or have a reference to the allocator. As they both need the reference, and it’s likely that future scenes will also require access to a texture allocator, we can create the texture allocator in the game class and pass it through the constructor to our scenes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/457b0df40734133e9aca1606d3e0e9e9/href">https://medium.com/media/457b0df40734133e9aca1606d3e0e9e9/href</a></iframe><p>We’ll also pass a resource allocator to the SceneSplashScreen.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c80393f257088ce07a7e26f0fbde2ba9/href">https://medium.com/media/c80393f257088ce07a7e26f0fbde2ba9/href</a></iframe><p><strong>Comment #1</strong>: we assume that this is the first time we will be using the logo so this scene will add it to the texture allocator.</p><p>Now we need to pass the texture allocator to our splash screen and game scene in the Game class constructor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43640005801368e3bfc42414acd48b4f/href">https://medium.com/media/43640005801368e3bfc42414acd48b4f/href</a></iframe><p>We also need to create a reference to the texture allocator in our Game header. We’ll only have the one copy of the texture allocator for now but in future, we may want different systems to be responsible for their own resources.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/977351528d72ad5e96114e314dba9c89/href">https://medium.com/media/977351528d72ad5e96114e314dba9c89/href</a></iframe><p>Make sure you run the game to check we have not broken anything, and you should (fingers crossed) be greeted with the now familiar sprite.</p><p>Next tutorial we will look at one method of handling the large number of objects that our game will eventually have and then we will finally start making changes to what is displayed on screen when we start our animation system.</p><p>Thank you for reading 🙂</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*4blJT7Ei8NX4ZBOJCw_D7w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2ee23beab0c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/game-dev-series/that-adventure-game-9-resource-management-e2ee23beab0c">That Adventure Game 9: Resource Management</a> was originally published in <a href="https://medium.com/game-dev-series">That Adventure Game</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[That Adventure Game 8: Components Continued]]></title>
            <link>https://medium.com/game-dev-series/that-adventure-game-8-components-continued-dae9671a1da5?source=rss-766830793bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/dae9671a1da5</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[entity-component-system]]></category>
            <category><![CDATA[games-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[adventure-games]]></category>
            <dc:creator><![CDATA[that games guy]]></dc:creator>
            <pubDate>Mon, 23 Apr 2018 15:00:37 GMT</pubDate>
            <atom:updated>2022-03-13T08:02:19.069Z</atom:updated>
            <content:encoded><![CDATA[<h4>Transform our Adventure Game by adding a movement component.</h4><blockquote>This is part of an ongoing series where we write a complete 2D adventure game in C++ and SFML. Starting from the basics (game loops, rendering etc.), we’ll quickly move on to more advanced topics, such as handling collisions, Quadtrees, animations, ray tracing, and creating component-based objects. In the process, we’ll cover everything you need to create 2D games. You can download the source code from the projects <a href="https://github.com/thatgamesguy/that_game_engine">GitHub page</a>. If you haven’t read the intro to the series, you can check it out <a href="https://medium.com/@thatgamesguy/game-dev-0-introduction-3723bae0fa8f">here</a>.</blockquote><p>In this tutorial, we will re-implement the movement code that we previously used to move our sprite around the screen, but this time as a component. We’ll also create a transform component that will be attached to all of our games objects. This component will eventually store the sprites position, rotation, and scale (although it will only store its position initially).</p><p>Before we can move our sprite, we need a method of storing and changing an objects position. To accomplish this we will write a Transform class. This class will store our objects position and provide a method of retrieving and changing that position. Lets name it <strong>C_Transform </strong>(the initial ‘C_’ is used to show that it is a component).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0ce56729bad93864918ae808bd2cb07/href">https://medium.com/media/b0ce56729bad93864918ae808bd2cb07/href</a></iframe><p>This is the minimum functionality that we require for now. In the future, we’ll also want to be able to rotate and scale our object, as well as add parent objects (parent objects will let us implement object hierarchies, such as those found with Unity and other game engines).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*kk8B5KZlHqNE5PVl_Wuvqw.png" /><figcaption>Object hierarchy in Unity</figcaption></figure><p>The methods are straightforward. They are simple get and set methods for a vector2 that we will use to store our objects on-screen coordinates.</p><p>From this point forward, we want all objects to have a transform component without having to manually add the component every time we create an object. To accomplish this, we’ll edit our Object class constructor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/273df1a9110e2b4863972d22b958fdb9/href">https://medium.com/media/273df1a9110e2b4863972d22b958fdb9/href</a></iframe><p><strong>Comment #1: </strong>there are arguments for and against storing the transform component as a public variable. If you’re anything like me, then you’ve probably been told a hundred times (mostly at university) to always hide your variables behind getters and setters/accessors and mutators. I’ve chosen to make this public because it will be accessed often and although the overhead is minuscule for adding the get method, I don’t want it.</p><p>Not all objects we create will have a sprite component and therefore will not be visible to the player, so you may wonder why I would want them to have a position. Even if we’re not drawing an object, it can still be useful to know their position in the world; for example, we may have an off-screen object that instantiates projectiles. We don’t want it to be doing this the whole time the level is being played, so using its position we make sure that it only starts producing projectiles when the players character is within a certain distance.</p><p>Currently, we can update an objects position through its transform but this will not change the position of the objects sprite (if present). We want to be able to change the transforms position (and in future scale/rotation) and have our sprite update its position automatically. To do this, we’ll change our sprite class to make use of our new transform component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4728bfa1ef10ad2dd949b5a977514259/href">https://medium.com/media/4728bfa1ef10ad2dd949b5a977514259/href</a></iframe><p><strong>Comment #1</strong>: if we want to use the functionality of the Object class, we have to include the class in our sprite implementation. As it was forward declared, we do not currently have any knowledge of its inner workings (also known as methods/data) so we need to include the header in our implementation file.</p><p><strong>Comment #2</strong>: this sets the sprites position based on our newly created transform. Now whenever we change the position in the transform class our sprites position will also be updated. We perform this in LateUpdate as any modifications to an objects position should happen during Update, so we can be relatively sure that we are retrieving the correct position for this frame. In future we may want to change our sprite component (and any class that uses the objects position) to only update its position when required (i.e. a change in position has occurred) rather than every frame.</p><p>To see this in action lets create a movement component for our character, called <strong>C_KeyboardMovement</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b14b0f09617962f41e5c4fe8ec91281e/href">https://medium.com/media/b14b0f09617962f41e5c4fe8ec91281e/href</a></iframe><p>You may have noticed that the class has a moveSpeed variable. Generally, we don’t want the keyboard controller class to care/know about the players move speed and once we look into creating the games physics we will change this, but it’ll do for now.</p><p>Nothing is really new here, we are simply re-adding our movement code from previous tutorials into our new component.</p><p>With our movement code done (for now anyway) we need to add the new component to our player object in SceneGame:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c8be2adf44339cb484eced983f82712/href">https://medium.com/media/9c8be2adf44339cb484eced983f82712/href</a></iframe><p>Our game scene now overrides late update as we want to call our player objects late update (to ensure our sprites retrieves our transforms position).</p><p>And there you have it: we can, once again, move our character. But this time we are using our new component system. We’ll take a break from writing components in the next tutorial and instead tale a look at implementing a resource management system to handle our textures, audio, and font files.</p><p>There are a few reasons (mostly performance based) that we will probably, at some point in the future, update our component system so that it is more inline with the Entity Component System model (which was briefly discussed in the previous tutorial). If you’re interested, <a href="https://unity3d.com/unity/features/job-system-ECS">Unity is currently making a transition to an ECS model</a>.</p><p>Thank you for reading 🙂</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*4blJT7Ei8NX4ZBOJCw_D7w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dae9671a1da5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/game-dev-series/that-adventure-game-8-components-continued-dae9671a1da5">That Adventure Game 8: Components Continued</a> was originally published in <a href="https://medium.com/game-dev-series">That Adventure Game</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[That Adventure Game 7: Components]]></title>
            <link>https://medium.com/game-dev-series/that-adventure-game-7-components-7053ed257fbd?source=rss-766830793bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/7053ed257fbd</guid>
            <category><![CDATA[componentes]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[that games guy]]></dc:creator>
            <pubDate>Mon, 16 Apr 2018 15:00:24 GMT</pubDate>
            <atom:updated>2022-03-06T08:03:02.890Z</atom:updated>
            <content:encoded><![CDATA[<h4>Add a component system to the Adventure Game.</h4><blockquote>This is part of an ongoing series where we write a complete 2D adventure game in C++ and SFML. Starting from the basics (game loops, rendering etc.), we’ll quickly move on to more advanced topics, such as handling collisions, Quadtrees, animations, ray tracing, and creating component-based objects. In the process, we’ll cover everything you need to create 2D games. You can download the source code from the projects <a href="https://github.com/thatgamesguy/that_game_engine">GitHub page</a>. If you haven’t read the intro to the series, you can check it out <a href="https://medium.com/@thatgamesguy/game-dev-0-introduction-3723bae0fa8f">here</a>.</blockquote><p>If you’ve been following the tutorials up to this point, you’ll have a sprite that you can move around the screen using the keyboard. While this is a good start, in the not too distant future, we will want to add additional functionality to our player object. At the very least we will want our player to have health, physics, a bounding box for collisions, and a way to animate its sprites. This is where the component system comes in, the focus of todays tutorial.</p><p>The component design pattern helps to decouple systems as they are written and maintained separately. Instead of creating a huge class/inheritance hierarchy containing all the systems that represent a player; we create individual, flexible components, and then mix and match these to create the desired object (e.g. player, projectile, enemy etc.). To do this we will write separate classes that encapsulate the behaviour we want to implement, we call this functionality ‘components’.</p><p>If you’ve used the Unity engine before then you have almost certainly used components. Most classes you write are attached to a GameObject as a component. The screenshot below shows the default Unity camera object with a Transform, Camera, and Audio Listener component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*CLhvUMYWcZ4lbocFuGHduw.png" /></figure><p>As a side note, the way we implement components differs somewhat from an Entity Component System (ECS) that you may have heard of/implemented before. An ECS consists of three main systems:</p><ul><li>Entities: this normally provides a method of uniquely identifying a collection of components and systems as belonging to one object. We’ll implement this shortly as an ‘Object’ class.</li><li>Components: in an ECS model these are usually simple data objects that do not contain any complex logic. In our model, our components can be as complex as we like.</li><li>Systems: this is usually where all the logic and complexity is situated. It will perform actions using the data found in the components. In our implementation, we do not write separate systems as our components will contain all the logic they need.</li></ul><p>Before we create our components, we’ll define the <strong>Object</strong> class. This is similar to the ‘Entity’ class in the ECS model and it will contain and maintain a list of our components for each object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/766722b1fba663d18c040064f763ee92/href">https://medium.com/media/766722b1fba663d18c040064f763ee92/href</a></iframe><p>These methods will iterate over the components attached to our object and call the relevant Update and Draw functions. But before we can write their implementation, we need to create our <strong>Component</strong> class, which will become the base class of all future components.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a940bb2ea2fe5a23dad20e3dd499e16/href">https://medium.com/media/4a940bb2ea2fe5a23dad20e3dd499e16/href</a></iframe><p><strong>Comment #1: </strong>As our Object requires a reference to Component and Component requires a reference to Object; we <a href="https://en.wikipedia.org/wiki/Forward_declaration">forward declare</a> Object.</p><p>Now we have our Component class, we can write the code to add, and retrieve components in our <strong>Object </strong>class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d80d8e3c4508e26c23ab59e826572e46/href">https://medium.com/media/d80d8e3c4508e26c23ab59e826572e46/href</a></iframe><p><strong>Comment #1:</strong> As AddComponent and GetComponent are <a href="https://www.cplusplus.com/doc/oldtutorial/templates/)">template functions</a>, I’ve implemented them in the header. These functions will work with any class that inherits from Component and when we implement our first components it will become clear how we use these functions.</p><p><strong>Comment #2:</strong> Both template functions make use of <a href="https://www.cplusplus.com/reference/memory/dynamic_pointer_cast/">dynamic casting</a>. This will cast a superclass to a subclass. As we are using smart pointers, if the cast is invalid it will return an empty shared ptr.</p><p>Currently, we only allow a user to add a component of a certain type once. In future we may want to be more flexible and allow the user to add and retrieve multiple objects of the same type.</p><p>With our component data structure implemented, we can write our Awake, Start, Update, LateUpdate, and Draw methods of our Object class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7ae472b99fc23eb16aabcdd5cfacae1/href">https://medium.com/media/d7ae472b99fc23eb16aabcdd5cfacae1/href</a></iframe><p>We loop through our components in reverse order as the component vector can be changed in our update or draw calls with components adding/removing other components. If we iterated over the collection from start to end, removing a component will cause our index to point to what it thinks is the last component but is actually a memory address space it no longer owns.</p><p>To see how these systems work we first need to create a component. We’ll start by creating a simple sprite component. It will, as the name suggests, draw a sprite to the screen. We’ll call the class <strong>C_Sprite</strong>. Similarly to scenes, I prepend any component class with ‘C_’ to differentiate them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a06b01ee8b57d075c61b9acce930a72a/href">https://medium.com/media/a06b01ee8b57d075c61b9acce930a72a/href</a></iframe><p>Our component system is mostly complete, and we have one component ready to test. We can now update our <strong>SceneGame</strong> class to re-create our player character using the new component system.</p><p>Include our new classes in <strong>SceneGame.hpp</strong>:</p><pre>#include “Object.hpp&quot; <br>#include “C_Sprite.hpp&quot;</pre><p>We no longer need a reference to our viking sprite as we have a component to do that so replace the lines:</p><pre>sf::Texture vikingTexture; <br>sf::Sprite vikingSprite;</pre><p>With our new player object:</p><pre>std::shared_ptr&lt;Object&gt; player;</pre><p>Next, update the OnCreate method in <strong>SceneGame.cpp</strong> to remove the references to our recently deleted texture and add code to instantiate our new player object and add our first component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a871686a717d0aa796841260a9bdcb22/href">https://medium.com/media/a871686a717d0aa796841260a9bdcb22/href</a></iframe><p>This is how to add components to objects. When adding a component it returns a reference to the newly created component, in this example, once we have the reference to the sprite component, we pass it a file path so we can load a sprite.</p><p>As we no longer have references to the sprite in the SceneGameclass we need to delete the movement code in our Update method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db81e0ef09a3b47dd408bbecefdb969f/href">https://medium.com/media/db81e0ef09a3b47dd408bbecefdb969f/href</a></iframe><p>And draw our player in the draw method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69dcea3ee38fe40f9af9d8676585d3e5/href">https://medium.com/media/69dcea3ee38fe40f9af9d8676585d3e5/href</a></iframe><p>With those changes mage, SceneGame should now look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48c7034e185a9b71b03a81d560d3394a/href">https://medium.com/media/48c7034e185a9b71b03a81d560d3394a/href</a></iframe><p>If you run the game, the sprite will be drawn using our new component system. However, you can no longer move it as we’ve removed the movement code. This may seem like a step backwards in terms of functionality, however we have improved our code and prepared it for future expansion. In the next tutorial, we will re-implement the movement code in our new component system.</p><p>Thank you for reading 🙂</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*4blJT7Ei8NX4ZBOJCw_D7w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7053ed257fbd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/game-dev-series/that-adventure-game-7-components-7053ed257fbd">That Adventure Game 7: Components</a> was originally published in <a href="https://medium.com/game-dev-series">That Adventure Game</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[That Adventure Game 6: Scene Management]]></title>
            <link>https://medium.com/game-dev-series/that-adventure-game-6-scene-management-7a64c3e70b8d?source=rss-766830793bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a64c3e70b8d</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[adventure-games]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[that games guy]]></dc:creator>
            <pubDate>Mon, 09 Apr 2018 15:00:01 GMT</pubDate>
            <atom:updated>2022-02-27T07:01:54.251Z</atom:updated>
            <content:encoded><![CDATA[<h4>Make a splash(screen) by writing a scene manager for our Adventure Game.</h4><blockquote>This is part of an ongoing series where we write a complete 2D adventure game in C++ and SFML. Starting from the basics (game loops, rendering etc.), we’ll quickly move on to more advanced topics, such as handling collisions, Quadtrees, animations, ray tracing, and creating component-based objects. In the process, we’ll cover everything you need to create 2D games. You can download the source code from the projects <a href="https://github.com/thatgamesguy/that_game_engine">GitHub page</a>. If you haven’t read the intro to the series, you can check it out <a href="https://medium.com/@thatgamesguy/game-dev-0-introduction-3723bae0fa8f">here</a>.</blockquote><p>In this tutorial, we will extend our game by writing a scene management system. If you’ve used Unity (or a similar game engine), you’ll have noticed how you can separate the game logic into different scenes. Each scene has its own unique properties and objects and will contain the logic for a specific part of our game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J0HnkXe5BSFDqfvsmXs1CA.png" /><figcaption>Default Scene in Unity</figcaption></figure><p>Most, if not all games, employ a number of scenes; a main menu and a game scene at the very least. Typically, a game will also have a splash screen; as well as a pause, game over, and credits scene. You can also create separate scenes for different levels of your game.</p><p>There’s a lot of code to get through, so let’s start by creating a new class called <strong>Scene</strong>. This will be the parent class of all our scenes. This is an abstract class that wont be instantiated, instead we’ll create specific scenes that inherit from this class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b029f78a34b03e41224909d58612896/href">https://medium.com/media/8b029f78a34b03e41224909d58612896/href</a></iframe><p>OnCreate and OnDestroy are <a href="https://www.geeksforgeeks.org/pure-virtual-functions-and-abstract-classes/">pure virtual functions</a> to ensure that this class is not instantiated. These two methods will need to be implemented in any class that inherits from Scene. If you find that you are implementing any other method (or combination of methods) more often, then it may be wise to change those methods to pure virtual functions instead.</p><p>To manage our scenes, we will write a finite-state machine (FSM). A FSM stores one or more states (scenes in this instance) with only a single state active at one time. A FSM also has the ability to transition between states, which suits our needs perfectly.</p><p>You can find more information on FSMs <a href="https://gamedevelopment.tutsplus.com/tutorials/finite-state-machines-theory-and-implementation--gamedev-11867">here</a>. Our FSM will be very simple (we’ll build on it in future), so if you’ve never implemented a FSM before it shouldn’t be a issue. I will also be discussing FSMs in more detail in a future tutorial on game AI.</p><p>Create a <strong>SceneStateMachine</strong> class. This will be FSM responsible for maintaining our scenes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5b6f16872fb57d49686d8954bf476de/href">https://medium.com/media/e5b6f16872fb57d49686d8954bf476de/href</a></iframe><p>Implement the more straightforward methods first:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0897de695943e3801feb7300c1b0a2ce/href">https://medium.com/media/0897de695943e3801feb7300c1b0a2ce/href</a></iframe><p>These methods call the relevant methods in the current scene (if there is one).</p><p>We need to be able to add and remove scenes to our state machine. This is relatively simple as all we need to do is add/remove the item from our map and call our OnCreate and OnDestroy methods after creation and before destruction:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b012dc33be835c0bf974dcb7acfd2898/href">https://medium.com/media/b012dc33be835c0bf974dcb7acfd2898/href</a></iframe><p>When we add a scene to the state machine we return an unsigned int. This is the scenes id and is currently required to remove the scene from the state machine. Using an unsigned int as the maps keys gives us the ability to have a maximum of 4,294,967,295 scenes. This should be more than enough for our purposes (or nearly anyones I would imagine). I have consciously not added any <a href="https://en.wikipedia.org/wiki/Integer_overflow">overflow protection</a> here yet as this would just complicate the code and I don’t think we are in any danger of inserting more scenes than we have space allocated. You can also add duplicate scenes and retrieve different ids, which is something we can improve in future.</p><p>It is worth noting that the actual size of the int can vary depending on the compiler used. This will not be an issue for us as we will still be able to create a larger number of scenes that we are likely to ever use. If we wanted to ensure the size of the int is the same regardless of the system we are compiling on, then we would use fixed-sized data types (which we did when writing the Bitmask class in a previous tutorial).</p><p>Removing scenes is also relatively simple. As previously stated, it requires passing in the scene id that is provided when we add a scene to our state machine.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efffe5aac85f8dc81f7a063ec12c811b/href">https://medium.com/media/efffe5aac85f8dc81f7a063ec12c811b/href</a></iframe><p>This method attempts to find a key with the provided id. If found it is removed from our map after we call the scenes OnDestroy method. The OnDestroy method can be implemented in our scenes to perform any cleanup.</p><p>The last method we require is the SwitchTo method that transitions to a scene based on its id:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a714e0b0c3e481818611c3c1d863df24/href">https://medium.com/media/a714e0b0c3e481818611c3c1d863df24/href</a></iframe><p>Now we have our scene management system, we can create a couple of scenes for testing, starting with the splash screen. The splash screen will briefly display our logo before transitioning to another scene (which we will create shortly). Create a new class called <strong>SceneSplashScreen</strong>. I’ve started all scenes classes with the word ‘scene’, so I can easily find them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95be13bc8899d57ff8df03be7dce14b2/href">https://medium.com/media/95be13bc8899d57ff8df03be7dce14b2/href</a></iframe><p>It inherits the methods that we have to (OnCreate and OnDestroy) and want to (OnActivate, Update and Draw):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f78684e165453a9ceef2278a1ea2f43/href">https://medium.com/media/8f78684e165453a9ceef2278a1ea2f43/href</a></iframe><p>Next, we’ll create the game scene. Theres nothing new here, we are just moving all the logic from the Game class to our new scene.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/653c8dcef3cb51840b34b9f095352cc6/href">https://medium.com/media/653c8dcef3cb51840b34b9f095352cc6/href</a></iframe><p>The final change we need to make is to the <strong>Game</strong> class. Our Game class will be responsible for creating the scenes and updating our SceneStateMachine. We also need to remove the logic that is now implemented in the SceneGameclass.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89ed3e18635c3279983d8571bb44b521/href">https://medium.com/media/89ed3e18635c3279983d8571bb44b521/href</a></iframe><p>We no longer need a reference to Input as this is now implemented in our game scene.</p><p>In our Game class constructor, we will create two scenes, the splash and game scene.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/281f814adbcc14e782da6c5bf4e1e9a6/href">https://medium.com/media/281f814adbcc14e782da6c5bf4e1e9a6/href</a></iframe><p><strong>Comment #1: </strong>This creates a<a href="https://msdn.microsoft.com/en-us/library/hh279674.aspx"> smart pointer</a> to a splash screen scene. And the next line does the same but for a game scene.</p><p><strong>Comment #2: </strong>We add our newly created scenes to the state machine. This returns the scenes id within the state machine.</p><p><strong>Comment #3: </strong>Now that we have our game scenes id we can set the splash screen to transition to the game scene.</p><p><strong>Comment #4: </strong>We want the game to start at the splash screen, so we transition to that scene using its id.</p><p>We then need to call the relevant update and draw methods on our scene state machine.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/feeecbd07ae5ec42274ce8cb4f3b1ce3/href">https://medium.com/media/feeecbd07ae5ec42274ce8cb4f3b1ce3/href</a></iframe><p>When you run the game you’ll now be greeted with a splash screen for a few seconds before the game is loaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*RDSFpNeO8wnGguYO8coCPA.png" /></figure><p>In future, we may convert our scene system to make use of components; where each scene, rather than being its own class, will consist of a collection of ‘components’. These components are smaller logical units that can be mixed and matched to create scenes. This topic will be covered further in the next tutorial when we look at implementing an Entity Component System for our player object.</p><p>Thank you for reading 🙂</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*4blJT7Ei8NX4ZBOJCw_D7w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a64c3e70b8d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/game-dev-series/that-adventure-game-6-scene-management-7a64c3e70b8d">That Adventure Game 6: Scene Management</a> was originally published in <a href="https://medium.com/game-dev-series">That Adventure Game</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[That Adventure Game 5: Real Time Input]]></title>
            <link>https://medium.com/game-dev-series/that-adventure-game-5-real-time-input-ac126552da53?source=rss-766830793bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac126552da53</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[sfml]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[that games guy]]></dc:creator>
            <pubDate>Mon, 02 Apr 2018 15:00:59 GMT</pubDate>
            <atom:updated>2022-02-20T07:02:57.256Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Jugnw8JjvACtbkRaRhosPw.png" /><figcaption>Sneak peek at our Adventure games house exterior</figcaption></figure><h4>Write an input manager to handle key states</h4><blockquote>This is part of an ongoing series where we write a complete 2D adventure game in C++ and SFML. Starting from the basics (game loops, rendering etc.), we’ll quickly move on to more advanced topics, such as handling collisions, Quadtrees, animations, ray tracing, and creating component-based objects. In the process, we’ll cover everything you need to create 2D games. You can download the source code from the projects <a href="https://github.com/thatgamesguy/that_game_engine">GitHub page</a>. If you haven’t read the intro to the series, you can check it out <a href="https://medium.com/@thatgamesguy/game-dev-0-introduction-3723bae0fa8f">here</a>.</blockquote><p>In this tutorial, we will begin to write an Input manager. We will look at recording keyboard input (controller support will be added in a later tutorial) and how to differentiate between a key that has just been pressed or released.</p><p>Create a new class called <strong>Input</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e5b6c11c99c7b9dda0a2a7c2cd47552/href">https://medium.com/media/8e5b6c11c99c7b9dda0a2a7c2cd47552/href</a></iframe><p>This summarises what we want from our input system. It wont build right now, as it does not know what a ‘Key’ is. So lets create that and also add an Update method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34079ed6eddca5f4393c160aba5ead5b/href">https://medium.com/media/34079ed6eddca5f4393c160aba5ead5b/href</a></iframe><p>The Key enum will hold every key we are interested in (currently that’s not many but will grow as we go). We have specified a value for each entry as we will use these values as bit position using the <a href="https://thatgamesguy.co.uk/game-engine-dev-4/">Bitmask</a> class that we created in the previous tutorial.</p><p>The update method will be responsible for polling the keys and determining which keys have been pressed that frame. For this to work, it needs a way of storing the status of the keys, which is where our <strong>Bitmask</strong> class comes in.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20afc3d64049f6072b7825376d7f101f/href">https://medium.com/media/20afc3d64049f6072b7825376d7f101f/href</a></iframe><p>We create two Bitmask variables: one to store the keys status this frame, and another to store the previous frames key status. We store two frames worth of data, so that we can determine if a key was just released or pressed by checking its current status against last frames status (I’ll go into more detail on this shortly). Update the bitmasks in the Update method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e71c4ef95ce90870f6163304ec92f8d2/href">https://medium.com/media/e71c4ef95ce90870f6163304ec92f8d2/href</a></iframe><p><strong>Comment #1: </strong>First we set lastFramesKeys bits to what is currently stored in thisFramesKeys bits. This stores the previous frames keys status as we are about to change the contents of thisFramesKeys.</p><p><strong>Comment #2: </strong>This will set or clear a bit depending on if the left key is being pressed. It calls the overloaded function ‘SetBit’ in the Bitmask class. This functions takes two parameters, the position of the bit and a boolean flag used to determine whether to set a bit to 1 or 0 (true or false). For the position parameter we use the keys enum int value (set when we created the enum), and for the boolean flag we call an SFML provided input method ‘isKeyPressed’; this will return true if the specified keys are pressed and therefore set our bit to 1 (key pressed) or 0 (key not pressed).</p><p>This is performed for each of they keys we are interested in. Here are a few examples of what our bitmask could look like after a typical update:</p><p>Left (pos 1) and Down (pos 4) keys pressed:</p><pre>0000 0000 0000 0000 0000 0000 0000 1010</pre><p>Up (pos 3) and Down (pos 4) keys pressed:</p><pre>0000 0000 0000 0000 0000 0000 0000 1100</pre><p>All keys pressed:</p><pre>0000 0000 0000 0000 0000 0000 0011 1110</pre><p>As you can see from the above examples, for each of our bitmasks (current and previous frames), we are only using 5 out of a possible 32 bits. In future this will not be too much of an issue as we expand the number of keys we are interested in, but it is definitely something to be aware of. We may want to create a reduced version of our bitmask or we may even find that we want to respond to more than 31 (32 minus the key::None option) different keys and create a larger bitmask.</p><p>Now that we store the status of our keys, lets implement the methods for querying that data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c50171a6dee086c220ff567b8983fc94/href">https://medium.com/media/c50171a6dee086c220ff567b8983fc94/href</a></iframe><p>IsKeyPressed will recognise a pressed key as long as its held down, whereas the other two methods only work for one frame; so if the keys status is not queried that frame the state change will be missed.</p><p>Now that we have implemented the basics of our Input class, we can integrate the system in our game.</p><p>We need to ensure our Input class is updated, we’ll do this by adding a new ‘CaptureInput’ method to our Gameclass.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd459679997bd4a1933ff8248d3780b5/href">https://medium.com/media/bd459679997bd4a1933ff8248d3780b5/href</a></iframe><p>We then call this in the main game loop:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edb82b73751b465de88c3f1dfc779881/href">https://medium.com/media/edb82b73751b465de88c3f1dfc779881/href</a></iframe><p>As we are now capturing keyboard input we can move our viking in the Update method of the <strong>Game</strong> class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fbf7714981745af18709ef06cc1adf7/href">https://medium.com/media/9fbf7714981745af18709ef06cc1adf7/href</a></iframe><p><strong>1. </strong>This is where we call our new input class. We call the IsKeyPressed method as we want to move the sprite as long as the specified key is pressed.</p><p><strong>2. </strong>We need to scale our movement by deltaTime, for more information see my previous tutorial on frame-independent movement.</p><p>Now when you run the game, you will be able to move the sprite around the screen using the arrow keys or WASD. You can also also change the input method calls to IsKeyDown (the character will only move once when a key is pressed) or IsKeyUp (the character will only move once when the key is released) to test that functionality.</p><p>In the next tutorial, we will start writing a scene management system.</p><p>Thank you for reading 🙂</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*4blJT7Ei8NX4ZBOJCw_D7w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac126552da53" width="1" height="1" alt=""><hr><p><a href="https://medium.com/game-dev-series/that-adventure-game-5-real-time-input-ac126552da53">That Adventure Game 5: Real Time Input</a> was originally published in <a href="https://medium.com/game-dev-series">That Adventure Game</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[That Adventure Game 4: Bitmasks]]></title>
            <link>https://medium.com/game-dev-series/that-adventure-game-4-bitmasks-6dc1e7b20fe1?source=rss-766830793bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/6dc1e7b20fe1</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[bit]]></category>
            <category><![CDATA[games-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[that games guy]]></dc:creator>
            <pubDate>Mon, 26 Mar 2018 15:00:25 GMT</pubDate>
            <atom:updated>2022-02-13T13:03:13.211Z</atom:updated>
            <content:encoded><![CDATA[<h4>Delve into the world of bits and bitwise operations</h4><blockquote>This is part of an ongoing series where we write a complete 2D adventure game in C++ and SFML. Starting from the basics (game loops, rendering etc.), we’ll quickly move on to more advanced topics, such as handling collisions, Quadtrees, animations, ray tracing, and creating component-based objects. In the process, we’ll cover everything you need to create 2D games. You can download the source code from the projects <a href="https://github.com/thatgamesguy/that_game_engine">GitHub page</a>. If you haven’t read the intro to the series, you can check it out <a href="https://medium.com/@thatgamesguy/game-dev-0-introduction-3723bae0fa8f">here</a>.</blockquote><p>In this tutorial, we are going to delve into the world of bits and bitwise operations. We will create a bitmask class that will be useful throughout our games, including in our input system that we will be starting in the next tutorial.</p><p>As we will be jumping straight into discussing operations we can perform on bits, it may be helpful to refresh your memory on what bits actually are. I recommend reading this <a href="https://computer.howstuffworks.com/bytes.htm">tutorial</a>.</p><p>Bitwise operations are any operations performed on ints and unsigned ints at the binary level, that change the values of individual bits.</p><p>It is easiest to explain what bitwise operators are by providing examples of each operation, therefore the table below outlines the bitwise operators we can make use of in C/C++ and provides an example of each one. I’ll provide additional examples when we discuss the implementation of our <strong>Bitmask</strong> class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*oGHQ-RfUlmzoJyAZekT_nw.png" /></figure><p>You may notice that some bitwise operators look similar to there logical counterparts (for example &amp; vs &amp;&amp;, and | vs ||), and they do perform a similar function just on a smaller scale.</p><p>Start by creating a class called <strong>Bitmask</strong>. This class will handle all of our bit manipulation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddfe144542e022be5f91b0191440ca9e/href">https://medium.com/media/ddfe144542e022be5f91b0191440ca9e/href</a></iframe><ol><li>We use uint32_t, a fixed-width 32-bit integer, to store our bitmask. This ensures that no matter what operating system our game is run on, it will always be 32 bits wide. More information on fixed-width integers can be found <a href="http://en.cppreference.com/w/cpp/types/integer">here</a>.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c85c4ec5a82e84a8abe45c2d793e2f23/href">https://medium.com/media/c85c4ec5a82e84a8abe45c2d793e2f23/href</a></iframe><ol><li>Sometimes it is easier to explain how something works with an example. Let’s say we call GetBit(2), so we want to know the true/false value of the bit at position 2. Let’s also assume the bitmask is 0101. The actual bitmask is 32 bits wide but for this example we’ll keep it simple and use 4 bits.</li></ol><pre>(bits &amp; (1 &lt;&lt; pos)) != 0 can be separated into the following steps:<br> <br>// We shift 1 by the specified position (2).  <br>// This gives us a 1 bit in the correct position. <br>1 &lt;&lt; 2 = 0100   </pre><pre>// We AND the result of the previous step with our bitmask.  <br>// The result will either contain a 1 at the specified position  <br>// (if the bit is turned on in our bitmask), or a  <br>// 0 (if the bit is turned off). <br>0100 &amp; 0101 = 0100   </pre><pre>// Therefore we know we have the bit at position 2 set to 1. <br>0100 != 0 = true</pre><p><strong>2. </strong>To set a bit to 1 we use the same shift to set a bit at the correct position as we did in the previous example, however this time we OR the result with our bitmask. For example, let’s say we call SetBit(1) and the bitmask is 0101:</p><pre>// This sets a 1 at the correct position <br>// (same as the previous example). <br>1 &lt;&lt; 1 = 0010 </pre><pre>// Our new bitmask (0111) contains all the 1&#39;s <br>// it did initially plus we have now set the bit <br>// at position one to 1. </pre><pre>0010 | 0101 = 0111</pre><p>We then OR with our bitmask. This will have one of two actions; firstly if our bitmask does not have a bit set in the position 1 then our new bitmask will not have that bit set (as we are using an OR), or if we already had the bit set the OR will do nothing and our bitmask will remain the same.</p><p><strong>3. </strong>Clearing a bit uses the shift again, but this time we invert its bits, using ones complement, before creating a new bitmask by ANDing the result with our current bitmask. For example, let’s say we call ClearBit(0) and the bitmask is 0101:</p><pre>1 &lt;&lt; 0 = 0001 </pre><pre>// This inverts the bits, so all bits but the <br>// position we&#39;ve requested to clear are set to 1. </pre><pre>~0001 = 1110 </pre><pre>1110 &amp; 0101 = 0100</pre><p>Our new bitmask has the bit at position 0 converted from 1 to 0.</p><p>These are the only methods we’ll need for the foreseeable future, although as with everything we write at this stage, we will probably be extending it in future.</p><p>It may not be too obvious how we are going to make use of this class at the moment, but we will shortly find out as we look at creating an input system for our game in the next tutorial.</p><p>As always, if you have any suggestions for what you would like covered or are having any trouble with the code then let me know in the comments.</p><p>Thank you for reading 🙂</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*4blJT7Ei8NX4ZBOJCw_D7w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6dc1e7b20fe1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/game-dev-series/that-adventure-game-4-bitmasks-6dc1e7b20fe1">That Adventure Game 4: Bitmasks</a> was originally published in <a href="https://medium.com/game-dev-series">That Adventure Game</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>