Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

OpenGL Game Development By Example
OpenGL Game Development By Example
OpenGL Game Development By Example
Ebook701 pages3 hours

OpenGL Game Development By Example

Rating: 0 out of 5 stars

()

Read preview

About this ebook

Design and code your own 2D and 3D games efficiently using OpenGL and C++

About This Book

- Create 2D and 3D games completely, through a series of end-to-end game projects
- Learn to render high performance 2D and 3D graphics using OpenGL
- Implement a rudimentary game engine using step-by-step code

Who This Book Is For

If you are a prospective game developer with some experience using C++, then this book is for you. Both prospective and experienced game programmers will find nuggets of wisdom and practical advice as they learn to code two full games using OpenGL, C++, and a host of related tools.

What You Will Learn

- Set up your development environment in Visual Studio using OpenGL
- Use 2D and 3D coordinate systems
- Implement an input system to handle the mouse and the keyboard
- Create a state machine to handle complex changes in the game
- Load, display, and manipulate both 2D and 3D graphics
- Implement collision detection and basic physics
- Discover the key components needed to complete a polished game
- Handle audio files and implement sound effects and music

In Detail

OpenGL is one of the most popular rendering SDKs used to develop games. OpenGL has been used to create everything from 3D masterpieces running on desktop computers to 2D puzzles running on mobile devices. You will learn to apply both 2D and 3D technologies to bring your game idea to life.
There is a lot more to making a game than just drawing pictures and that is where this book is unique! It provides a complete tutorial on designing and coding games from the setup of the development environment to final credits screen, through the creation of a 2D and 3D game.
The book starts off by showing you how to set up a development environment using Visual Studio, and create a code framework for your game. It then walks you through creation of two games–a 2D platform game called Roboracer 2D and a 3D first-person space shooter game–using OpenGL to render both 2D and 3D graphics using a 2D coordinate system. You'll create sprite classes, render sprites and animation, and navigate and control the characters. You will also learn how to implement input, use audio, and code basic collision and physics systems. From setting up the development environment to creating the final credits screen, the book will take you through the complete journey of creating a game engine that you can extend to create your own games.

Style and approach

An easy-to-follow guide full of code examples to illustrate every concept and help you build a 2D and 3D game from scratch, while learning the key tools that surround a typical OpenGL project.
LanguageEnglish
Release dateMar 8, 2016
ISBN9781783288205
OpenGL Game Development By Example

Related to OpenGL Game Development By Example

Related ebooks

Computers For You

View More

Related articles

Reviews for OpenGL Game Development By Example

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    OpenGL Game Development By Example - Madsen Robert

    Table of Contents

    OpenGL Game Development By Example

    Credits

    About the Authors

    About the Reviewers

    www.PacktPub.com

    Support files, eBooks, discount offers, and more

    Why subscribe?

    Free access for Packt account holders

    Preface

    What this book covers

    What you need for this book

    Who this book is for

    Conventions

    Reader feedback

    Customer support

    Downloading the example code

    Errata

    Piracy

    Questions

    1. Building the Foundation

    Introducing the development environment

    A quick look at Visual Studio

    Start screen

    The Solution Explorer panel

    The Standard Toolbar panel

    The code window

    The output window

    Starting your project

    The game loop

    The game structure

    Initialization

    The game loop

    Shutdown

    Creating the game structure

    Port of access

    The Windows message loop

    Introducing OpenGL

    What is OpenGL?

    The other GL

    Downloading OpenGL

    Adding OpenGL to the project

    Linking to the OpenGL library

    Summary

    2. Your Point of View

    Plotting your revenge

    The OpenGL coordinate system

    Making your point

    Understanding the code

    Header files

    Initializing OpenGL

    The main entry point

    The update function

    Drawing the points

    Running the program

    Stretching your point

    Getting primitive

    A triangle by any other name

    A primitive example

    From triangles to models

    Introducing textures

    Using textures to fill the triangles

    A matter of reference

    Hanging out in the quad

    Coding the quad

    Rendering a texture

    Loading the texture

    Texture wrapping

    Creating a textured quad

    Putting the pieces together

    Summary

    3. A Matter of Character

    Spritely speaking

    Sprites versus non-sprites

    Flipbook animation

    Framed animation

    Creating sprites

    Working with PNGs

    Linking to the SOIL library

    Including the SOIL header file

    Opening an image file

    Coding a sprite class

    Creating sprite frames

    Saving each frame

    Loading a sprite from individual textures

    Creating a sprite sheet

    Loading a sprite sheet

    Loading our sprites

    Rendering

    Adding a render to the game loop

    Implementing the main Render function

    Implementing Render in the Sprite class

    UV mapping

    One more detail

    A moving example

    Adding update to the game loop

    Implementing the main Update call

    Implementing Update in the Sprite class

    Character movement

    Using delta time

    Calculating delta time

    Flipping

    Scrolling the background

    Using an atlas

    Summary

    4. Control Freak

    A penny for your input

    The keyboard input

    Using the mouse

    Touch

    Other inputs

    Someone is listening

    The WndProc event listener

    Handling the message queue

    Handling mouse and keyboard inputs

    Creating the Input class

    Virtual key codes

    Querying for input

    Implementing the Input class

    Adding input to the game loop

    Processing our input

    Changes to the Sprite class

    Graphical User Interface

    Creating a button

    Enhancing the Input class

    Adding UI elements to the list

    Checking each UI element

    Pushing your buttons

    Adding our pauseButton

    State management

    Creating a state manager

    Pausing the game

    Summary

    5. Hit and Run

    Out of bounds!

    Getting anchored

    Collision rectangles

    Embedding

    Fixing the background

    Collideables

    Ready to score

    A friend indeed

    Time to spawn

    Circular collision detection

    The Pythagorean Theorem

    Adding the circular collision code

    Why use circular collision detection?

    Wiring in the collision detection

    Rectangular collision detection

    The enemy within

    Spawning the enemy

    Adding the rectangular collision code

    Wiring continued

    Summary

    6. Polishing the Silver

    The state of the game

    State machines

    Why do we need a state machine?

    Planning for state

    Defining the new state

    Implementing the state machine

    Making a splash

    Creating the splash screen

    Defining the splash screen

    Loading our resources

    What's on the menu?

    Creating the menu

    Defining the menu buttons

    Getting some credit

    Creating the credits screen

    Getting back to the main menu

    Working with fonts

    Creating the font

    Drawing text

    Wiring in the font support

    Level up!

    Displaying the score

    Game progression

    Defining game levels

    Game stats

    The next level screen

    Continuing the game

    Game over

    The game over screen

    Replaying the game

    Summary

    7. Audio Adrenaline

    Bits and bytes

    A sound by any other name

    Making noise

    Revving up your engine

    Accessing the FMOD .dll file

    Linking to the library

    Point to the include files

    Initializing FMOD

    Virtual channels

    Channel priority

    Bleeps and bloops

    Sound effects

    Setting up the sounds

    Playing sounds

    UI feedback

    The sound of music

    Cleaning up the house

    Release sprites

    Release input

    Releasing fonts

    Releasing audio

    Summary

    8. Expanding Your Horizons

    Into the third dimension!

    Simulating 3D

    Real 3D

    3D Coordinate Systems

    The camera

    Remember those home movies?

    Steady as she goes!

    The viewport

    Entering the matrix

    Vectors

    Combining vectors

    Identity matrix

    Coding in 3D

    Creating the project

    Retrieving OpenGL files

    Linking projects to OpenGL libraries

    Setting up the OpenGL window

    Including header files

    Defining global variables

    Creating a function to create the OpenGL window

    Sizing the OpenGL window

    Initializing the OpenGL window

    Creating a function to remove the OpenGL window

    Creating the OpenGL window

    Creating the Windows event handler

    The Game loop

    The finale

    Summary

    9. Super Models

    New Space

    A computer in a computer

    Drawing your weapons

    Getting primitive

    Drawing primitives

    Making your point

    Gl_Points

    Getting in line

    Gl_Lines

    Gl_Line_Strip

    Gl_Line_Loop

    Triangulation

    Gl_Triangles

    Gl_Triangle_Strip

    Gl_Triangle_Fan

    Being square

    Gl_Quads

    Gl_Quad_Strip

    Saving face

    Back to Egypt

    A modeling career

    Blending in

    Blender overview

    Building your spaceship

    Exporting the object

    Getting loaded

    Summary

    10. Expanding Space

    Creation 101

    Preparing the project

    Loading game objects

    The Model class header

    Implementing the Model class

    Modifying the game code

    Taking control

    Implementing input

    Asteroid slalom

    Setting up collision detection

    Turning on collision

    Summary

    11. Heads Up

    Mixing things up

    The saving state

    Push and pop

    Two state rendering

    A matter of state

    Adding the state machine

    Getting ready for a splash

    Creating the user interface

    Defining the text system

    Defining textures

    Wiring in render, update, and the game loop

    Summary

    12. Conquer the Universe

    A fun framework

    Setting up the Visual Studio project

    Setting up the Windows environment

    Setting up the OpenGL environment

    Setting up the game loop

    Texture mapping

    Loading the texture

    Rendering the cube

    Mapping operations

    Let there be light!

    Defining a light source

    The skybox

    Advanced topics

    Game physics

    AI

    The future

    Summary

    Index

    OpenGL Game Development By Example


    OpenGL Game Development By Example

    Copyright © 2016 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    First published: March 2016

    Production reference: 1010316

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham B3 2PB, UK.

    ISBN 978-1-78328-819-9

    www.packtpub.com

    Credits

    Authors

    Robert Madsen

    Stephen Madsen

    Reviewers

    Artemis Tsouflidou

    Simon W. J. Vanhauwaert

    Pantelis Lekakis

    Commissioning Editor

    Julian Ursell

    Acquisition Editor

    Shaon Basu

    Content Development Editor

    Siddhesh Salvi

    Technical Editor

    Parag Topre

    Copy Editor

    Priyanka Ravi

    Project Coordinator

    Paushali Desai

    Proofreader

    Safis Editing

    Indexer

    Monica Ajmera Mehta

    Graphics

    Disha Haria

    Production Coordinator

    Nilesh Mohite

    Cover Work

    Nilesh Mohite

    About the Authors

    Robert Madsen is an accomplished game programmer, with dozens of published games to his credit. He started programming in 1979, and he has been a programmer for all of his professional life. He entered the game industry in 2004, and he founded SynapticSwitch, LLC in 2010. As studio director, he continues to code while also managing the broader needs of an independent game development studio.

    Stephen Madsen completed his degree in game development from Full Sail Real World Education in 2007, beginning his first job as a game programmer in 2008. He then joined SynapticSwitch, LLC as the lead software engineer in 2012. He has developed and published many titles on the mobile, console, and personal computer platforms with OpenGL being the foundational rendering technology for most of these platforms.

    About the Reviewers

    Artemis Tsouflidou is a game developer based in London, and she has experience in gameplay programming. She studied computer engineering at the University of Thessaly in Greece, and she continued her studies at Goldsmiths University where she earned a master's degree in computer games. She is interested in programming and game development.

    Simon W. J. Vanhauwaert is a Belgian game development programmer. He graduated in digital arts and entertainment, and he is currently professionally employed in the UK.

    Pantelis Lekakis has been in the game industry for 4 years now, and he has been actively programming and developing his own projects since 2002.

    His experience lies in rendering and game engines, and he has worked with various versions of Direct3D and OpenGL.

    www.PacktPub.com

    Support files, eBooks, discount offers, and more

    For support files and downloads related to your book, please visit www.PacktPub.com.

    Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at for more details.

    At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

    https://www2.packtpub.com/books/subscription/packtlib

    Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

    Why subscribe?

    Fully searchable across every book published by Packt

    Copy and paste, print, and bookmark content

    On demand and accessible via a web browser

    Free access for Packt account holders

    If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.

    Preface

    Welcome to OpenGL Game Development Blueprints! We are excited that you chose this book as your guide to both OpenGL and game development. This section will provide you with a brief preview of each chapter, followed by the technologies that are required to complete the work that is presented in the book. Finally, we will discuss the target audience for this book so that you will know whether this book is right for you.

    What this book covers

    Chapter 1, Building the Foundation, guides you through creating the code framework for the game. Games use a particular structure that is known as the game loop. By the end of this chapter, you will understand and have created the game loop for the game as well as initialized the required OpenGL elements.

    Chapter 2, Your Point of View, introduces you to the first project in the book—creating a 2D platform game. The first step in this project will be to define the type of view that is required by OpenGL, and render the background of the game.

    Chapter 3, A Matter of Character, covers the creation of sprites that move on the screen. 2D frame-based animations are the core of any 2D game, and you will learn how to create simple graphics and render them to the screen.

    Chapter 4, Control Freak, teaches you how to build an input system that will allow you to control the main character and other aspects of the game. You will also create a basic user interface that allows you to start the game and navigate to various options.

    Chapter 5, Hit and Run, covers collision detection. You will learn how to stop the character from falling through the ground, how to land on objects, and how to detect whether enemies have hit you or have been hit by player weapons. By the end of this chapter, you will be able to play the game for the first time.

    Chapter 6, Polishing the Silver, covers the topics that make a game presentable (but are often overlooked by novice developers). You will learn how to implement a scoring system, game over and game won scenarios, and simple level progression. This chapter will conclude the 2D project of the book.

    Chapter 7, Audio Adrenaline, guides you through implementing sound effects and music in the game. We will provide links to some audio files that you can use in your game.

    Chapter 8, Expanding Your Horizons, will start the second project of the book—a 3D first-person space shooter. At the end of this chapter you will have created a new project, starting the framework for a 3D game.

    Chapter 9, Super Models, introduces you to the concepts of 3D art and modeling, and then guides you through the process of loading 3D models into the game environment. Although you will be able try your hand at creating a 3D model, the resources that are required for the game will be provided online.

    Chapter 10, Expanding Space, expands on many of the concepts that were covered in the 2D segment of the book and applies them to a 3D world. Movement and collision detection are revamped to take this new dimension into consideration. An input scheme to move in 3D space is implemented. By the end of this chapter, you will be able to control a 3D model in 3D space.

    Chapter 11, Heads Up, guides you through creating a 2D user interface on top of the 3D world. You will create a menu system to start and end the game, as well as a heads-up-display (HUD) that shows the score and stats in game. By the end of this chapter, you will have created a playable 3D shooter game.

    Chapter 12, Conquer the Universe, introduces you to some of the more advanced concepts that were beyond the scope of the book, and it gives you some direction to advance your skills.

    What you need for this book

    Each chapter in the book will have exercises that you will need to code. Each exercise is a building block toward creating your first game using OpenGL. It is vitally important that you actually write the code. In our experience, you can't learn any kind of computer programming without actually writing code. Don't just read the book, do the book!

    The first chapter of the book will go through the details of setting up a development environment so that you can code the examples in the book. In general, you will need the following:

    A Windows-based personal computer: You could use a Mac, but the examples used in the book are based on a Windows 10 operating system.

    A copy of Visual Studio: We will show you how to obtain and install this for free in chapter one, or you can go to http://www.visualstudio.com/downloads/download-visual-studio-vs right now. Again, you could use another development tool and compiler, but you are on your own to set it up.

    A 2D image editor program: We recommend GIMP, which you can download for free at http://www.gimp.org/.

    A 3D modeling program: We recommend Blender, which you can download for free at http://www.blender.org/.

    An Internet connection: You could complete the exercises without this, but an Internet connection is very useful for looking up additional resources.

    Some free time and dedication!

    That's it! The good news is that as long as you have a personal computer, the technology and tools that are used to create games using OpenGL are completely free!

    Who this book is for

    If you are reading this book, it is pretty obvious that you are interested in game development. You have either heard of OpenGL or perhaps even used it, and you want to learn more. Finally, you are already a programmer in some computer language or you want to be.

    Does this sound like you? Read on!

    This book assumes that you have some familiarity with computer programming in the C++ computer language. If you have programmed in some other language, such as C#, Java, JavaScript, or PHP, then you are pretty familiar with the constructs of the C++ language. Nevertheless, if have never programmed in C++ then you may need to brush up on your skills. You can try Microsoft Visual C++ Windows Applications by Example, also published by Packt Publishing. If you feel comfortable with programming in general, but have not coded in C++, you can look at the free online C++ tutorials at http://www.cplusplus.com/doc/tutorial/.

    We don't assume that you have any knowledge of OpenGL—that is what this book is going to give you. We start by explaining the basic concepts of OpenGL and move through more advanced concepts by example. As you learn, you will also code, providing you with the opportunity to put what you have learned into practice. This book won't make you an OpenGL expert overnight, but it will give you the foundation to understand and use OpenGL. At the end of this book, we will give you some pointers to other resources that will allow you to learn even more about OpenGL.

    We also don't assume that you have any experience developing games. This book is rather unique in that it provides you with a primer to learn OpenGL and a primer to learn game development. There are many books out there that teach OpenGL, but most do so within a more academic or theoretical framework. We felt that it was better to teach you OpenGL while you were using it to create an actual game. Actually, you will code two games: one in 2D, and one in 3D. Two for the price of one!

    Conventions

    In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

    Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: As usual, change the middle line in update to call drawQuad.

    A block of code is set as follows:

    void CheckCollisions()

    {

      if (player->IntersectsRect(pickup))

      {

        pickup->IsVisible(false);

        pickup->IsActive(false);

        player->SetValue(player->GetValue() + pickup->GetValue());

        pickupSpawnTimer = 0.0f;

      }

    }

    When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

    pause->Update(p_deltaTime);

      resume->Update(p_deltaTime);

     

      pickup->Update(p_deltaTime);

      SpawnPickup(p_deltaTime);

     

      CheckCollisions();

     

    }

    New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: For the Configuration drop-down box, make sure you select All Configurations.

    Note

    Warnings or important notes appear in a box like this.

    Tip

    Tips and tricks appear like this.

    Reader feedback

    Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

    To send us general feedback, simply e-mail <feedback@packtpub.com>, and mention the book's title in the subject of your message.

    If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

    Customer support

    Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

    Downloading the example code

    You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

    Errata

    Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

    To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

    Piracy

    Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

    Please contact us at <copyright@packtpub.com> with a link to the suspected pirated material.

    We appreciate your help in protecting our authors and our ability to bring you valuable content.

    Questions

    If you have a problem with any aspect of this book, you can contact us at <questions@packtpub.com>, and we will do our best to address the problem.

    Chapter 1. Building the Foundation

    Building a game is like building a house. Except this is a crazy house with rooms sticking out everywhere, and at any time someone might decide to add another room just here, and remove a room over there. You had better have a good foundation!

    This chapter will take you through the process of setting up the foundation to build your game. You will learn, how to set up a development environment using Visual Studio. Next, you will set up the game loop, which is the foundation for every game ever created. Finally, you will set up the development environment to use OpenGL as your rendering engine.

    Introducing the development environment

    The development environment is the

    Enjoying the preview?
    Page 1 of 1