Kelvin Sung, Jebediah Pavleas, Matthew Munson and Jason Pace

Build Your Own 2D Game Engine and Create Great Web Games

Using HTML5, JavaScript, and WebGL2

2nd ed.
With Original Dye character designs by Nathan Evers Other game character and art design by Kasey Quevedo Figures and illustrations by Clover Wai
Kelvin Sung
Bothell, WA, USA
Jebediah Pavleas
Kenmore, WA, USA
Matthew Munson
Lake Forest Park, WA, USA
Jason Pace
Portland, OR, USA
ISBN 978-1-4842-7376-0e-ISBN 978-1-4842-7377-7
© Kelvin Sung, Jebediah Pavleas, Matthew Munson, and Jason Pace 2022
Standard Apress
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.
The publisher, the authors and the editors are safe to assume that the advice and information in this book are believed to be true and accurate at the date of publication. Neither the publisher nor the authors or the editors give a warranty, express or implied, with respect to the material contained herein or for any errors or omissions that may have been made. The publisher remains neutral with regard to jurisdictional claims in published maps and institutional affiliations.

This Apress imprint is published by the registered company APress Media, LLC part of Springer Nature.

The registered company address is: 1 New York Plaza, New York, NY 10004, U.S.A.

To my wife, Clover, and our girls, Jean and Ruth, for completing my life.

—Kelvin Sung

To my family, for their eternal support throughout my life.

—Jebediah Pavleas

To my mom, Linda, for showing me the value of having fun at work.

—Jason Pace

Introduction

Welcome to Build Your Own 2D Game Engine and Create Great Web Games. Because you have picked up this book, you are likely interested in the details of a game engine and the creation of your own games to be played over the Internet. This book teaches you how to build a 2D game engine by covering the involved technical concepts, demonstrating sample implementations, and showing you how to organize the large number of source code and asset files to support game development. This book also discusses how each covered technical topic area relates to elements of game design so that you can build, play, analyze, and learn about the development of 2D game engines and games. The sample implementations in this book are based on HTML5, JavaScript, and WebGL2, which are technologies that are freely available and supported by virtually all web browsers. After reading this book, the game engine you develop and the associated games will be playable through a web browser from anywhere on the Internet.

This book presents relevant concepts from software engineering, computer graphics, mathematics, physics, game development, and game design—all in the context of building a 2D game engine. The presentations are tightly integrated with the analysis and development of source code; you’ll spend much of the book building game-like concept projects that demonstrate the functionality of game engine components. By building on source code introduced early on, the book leads you on a journey through which you will master the basic concepts behind a 2D game engine while simultaneously gaining hands-on experience developing simple but working 2D games. Beginning from Chapter 4, a “Design Considerations” section is included at the end of each chapter to relate the covered technical concepts to elements of game design. By the end of the book, you will be familiar with the concepts and technical details of 2D game engines, feel competent in implementing functionality in a 2D game engine to support commonly encountered 2D game requirements, and capable of considering game engine technical topics in the context of game design elements in building fun and engaging games.

New in the Second Edition

The key additions to the second edition include JavaScript language and WebGL API update and dedicated chapters with substantial details on physics and particle systems components.

All examples throughout the entire book are refined for the latest features of the JavaScript language. While some updates are mundane, for example, prototype chain syntax replacements, the latest syntax allows significant improvements in overall presentation and code readability. The new and much cleaner asynchronous support facilitated a completely new resource loading architecture with a single synchronization point for the entire engine (Chapter 4). The WebGL context is updated to connect to WebGL 2.0. The dedicated chapters allow more elaborate and gradual introduction to the complex physics and particle systems components. Detailed mathematical derivations are included where appropriate.

Who Should Read This Book

This book is targeted toward programmers who are familiar with basic object-oriented programming concepts and have a basic to intermediate knowledge of an object-oriented programming language such as Java or C#. For example, if you are a student who has taken a few introductory programming courses, an experienced developer who is new to games and graphics programming, or a self-taught programming enthusiast, you will be able to follow the concepts and code presented in this book with little trouble. If you’re new to programming in general, it is suggested that you first become comfortable with the JavaScript programming language and concepts in object-oriented programming before tackling the content provided in this book.

Assumptions

You should be experienced with programming in an object-oriented programming language, such as Java or C#. Knowledge and expertise in JavaScript would be a plus but are not necessary. The examples in this book were created with the assumption that you understand data encapsulation and inheritance. In addition, you should be familiar with basic data structures such as linked lists and dictionaries and be comfortable working with the fundamentals of algebra and geometry, particularly linear equations and coordinate systems.

Who Should Not Read This Book

This book is not designed to teach readers how to program, nor does it attempt to explain the intricate details of HTML5, JavaScript, or WebGL2. If you have no prior experience developing software with an object-oriented programming language, you will probably find the examples in this book difficult to follow.

On the other hand, if you have an extensive background in game engine development based on other platforms, the content in this book will be too basic; this is a book intended for developers without 2D game engine development experience. However, you might still pick up a few useful tips about 2D game engine and 2D game development for the platforms covered in this book.

Organization of This Book

This book teaches how to develop a game engine by describing the foundational infrastructure, graphics system, game object behaviors, camera manipulations, and a sample game creation based on the engine.

Chapters 24 construct the foundational infrastructure of the game engine. Chapter 2 establishes the initial infrastructure by separating the source code system into folders and files that contain the following: JavaScript-specific core engine logics, WebGL2 GLSL–specific shader programs, and HTML5-specific web page contents. This organization allows ongoing engine functionality expansion while maintaining localized source code system changes. For example, only JavaScript source code files need to be modified when introducing enhancements to game object behaviors. Chapter 3 builds the drawing framework to encapsulate and hide the WebGL2 drawing specifics from the rest of the engine. This drawing framework allows the development of game object behaviors without being distracted by how they are drawn. Chapter 4 introduces and integrates core game engine functional components including game loop, keyboard input, efficient resource and game-level loading, and audio support.

Chapters 57 present the basic functionality of a game engine: drawing system, behavior and interactions, and camera manipulation. Chapter 5 focuses on working with texture mapping, including sprite sheets, animation with sprite sheets, and the drawing of bitmap fonts. Chapter 6 puts forward abstractions for game objects and their behaviors including per-pixel-accurate collision detection. Chapter 7 details the manipulation and interactions with the camera including programming with multiple cameras and supporting mouse input.

Chapters 811 elevate the introduced functionality to more advanced levels. Chapter 8 covers the simulation of 3D illumination effects in 2D game scenes. Chapter 9 discusses physically based behavior simulations. Chapter 10 presents the basics of particle systems that are suitable for modeling explosions. Chapter 11 examines more advanced camera functionality including infinite scrolling through tiling and parallax.

Chapter 12 summarizes the book by leading you through the design of a complete game based on the game engine you have developed.

Code Samples

Every chapter in this book includes examples that let you interactively experiment with and learn the new materials. You can access the source code for all the projects, including the associated assets (images, audio clips, or fonts), by clicking the Download Source Code button located at www.apress.com/9781484273760. You should see a folder structure that is organized by chapter numbers. Within each folder are subfolders containing Visual Studio Code (VS Code) projects that correspond to sections of this book.

Acknowledgments

This book project was a direct result of the authors learning from building games for the Game-Themed CS1/2: Empowering the Faculty project, funded by the Transforming Undergraduate Education in Science, Technology, Engineering, and Mathematics (TUES) Program, National Science Foundation (NSF) (award number DUE-1140410). We would like to thank NSF officers Suzanne Westbrook for believing in our project and Jane Prey, Valerie Bar, and Paul Tymann for their encouragements.

This second edition is encouraged by many students and collaborators. In particular, students from CSS452: Game Engine Development (see https://myuwbclasses.github.io/CSS452/) at the University of Washington Bothell have been the most critical, demanding, and yet supportive. Through the many games and API extension projects (see https://html5gameenginegroup.github.io/GTCS-Engine-Student-Projects/), it became clear that updates are required of the JavaScript and WebGL (Web Graphics Library) versions, the bottom-line synchronization mechanism, and, most significantly, the coverage of the physics engine. Fernando Arnez, our co-author from the first edition, taught us JavaScript. Yaniv Schwartz pointed us toward JavaScript async/await and promise. The discussions and collaborations with Huaming Chen and Michael Tanaya contributed directly to the chapter on game engine physics. Akilas Mebrahtom and Donald Hawkins constructed the extra example at the end of Chapter 9 illustrating potential presets for commonly encountered physical materials. The audio volume control was first investigated and integrated by Kyla NeSmith. Nicholas Carpenetti and Kyla NeSmith developed a user interface API for the initial game engine, which unfortunately did not make it into this edition. These and countless other feedbacks have contributed to the quality and improvements of the book’s content.

The hero character Dye and many of the visual and audio assets used throughout the example projects of the book are based on the Dye Hard game, designed for teaching concepts of objects and object-oriented hierarchy. The original Dye Hard development team members included Matthew Kipps, Rodelle Ladia, Chuan Wang, Brian Hecox, Charles Chiou, John Louie, Emmett Scout, Daniel Ly, Elliott White, Christina Jugovic, Rachel Harris, Nathan Evers, Kasey Quevedo, Kaylin Norman-Slack, David Madden, Kyle Kraus, Suzi Zuber, Aina Braxton, Kelvin Sung, Jason Pace, and Rob Nash. Kyle Kraus composed the background music used in the Audio Support project from Chapter 4, originally for the Linx game, which was designed to teach loops. The background audio for the game in Chapter 12 was composed by David Madden and arranged by Aina Braxton. Thanks to Clover Wai for the figures and illustrations.

We also want to thank Spandana Chatterjee for believing in our ideas, her patience, and continual efficient and effective support. A heartfelt thank-you to Mark Powers, for his diligence and lightning-fast email responses. Mark should learn about and consider the option of sleeping some of the time. Nirmal Selvaraj organized everything and ensured proper progress was ongoing.

Finally, we would like to thank Yusuf Pisan for his insightful, effective, and, above all, quick turnaround for the technical review.

All opinions, findings, conclusions, and recommendations in this work are those of the authors and do not necessarily reflect the views of the sponsors.

Table of Contents
About the Authors
Kelvin Sung

is a Professor with the Computing and Software Systems Division at the University of Washington Bothell (UWB). He received his Ph.D. in Computer Science from the University of Illinois at Urbana-Champaign. Kelvin’s background is in computer graphics, hardware, and machine architecture. He came to UWB from Alias|Wavefront (now part of Autodesk), where he played a key role in designing and implementing the Maya Renderer, an Academy Award–winning image generation system. At UWB, funded by Microsoft Research and the National Science Foundation, Kelvin’s work focuses on the intersection of video game mechanics, solutions to real-world problems, and supports for remote collaboration. Together with his students and colleagues, Kelvin has co-authored five books: one on computer graphics (Essentials of Interactive Computer Graphics: Concepts and Implementation, A.K. Peters, 2008) and the others on 2D game engines (Learn 2D Game Development with C#, Apress, 2013; Build Your Own 2D Game Engine and Create Great Web Games, Apress, October 2015; Building a 2D Game Physics Engine, Apress, 2016; and Basic Math for Game Development with Unity 3D, Apress, 2019).

 
Jebediah Pavleas
../images/334805_2_En_BookFrontmatter_Figb_HTML.jpg
received his Master of Science Degree in Computer Science and Software Engineering from the University of Washington Bothell (UWB) in 2016. He also received a Bachelor of Science Degree from UWB in 2012 and was the recipient of the Chancellor’s Medal for his class. During his graduate program, Jebediah interned for Microsoft Research’s Enable team where he contributed to their Eye-Gaze Wheelchair project (a wheelchair driven with only your eyes for those with ALS). He has co-authored three books on 2D games and game engines (Learn 2D Game Development with C#, Apress, 2013; Build Your Own 2D Game Engine and Create Great Web Games, Apress, October 2015; Building a 2D Game Physics Engine, Apress, 2016). During his time at UWB, his projects included an interactive math application that utilizes Microsoft’s Kinect sensor to teach algebra called Kinect Math. Relating to this and other projects, he co-authored publications in IEEE Computer and The Journal of Computing Sciences in Colleges (CCSC). Jebediah enjoys designing, building, and playing games of all kinds as well as adapting technology for improved accessibility for himself and others.
 
Matthew Munson

is a graduate student in the Computer Science and Software Engineering program at the University of Washington Bothell. He received undergraduate degrees in Computer Science and Software Engineering and Mechanical Engineering at the University of Washington Bothell in 2020. Matthew is interested in operating system development, networking, and embedded systems. As a research assistant, Matthew used cloud computing to analyze years of audio data recorded by hydrophones off the Oregon coast. This data was used to study the effects of climate change and shipping noise on marine mammals. Currently, Matthew is working on a networked augmented reality library that focuses on allowing users to view the same virtual scene from different perspectives.

 
Jason Pace

contributed to a wide range of games as a producer, designer, and creative director over 15 years in the interactive entertainment industry, from ultra-casual puzzlers on mobile to Halo on Xbox. As a designer, Jason builds game mechanics and systems that start from a simple palette of thoughtful interactions (known as the core gameplay loop), progressively introducing variety and complexity to create interactive experiences that engage and delight players while maintaining focus on what makes each e-game uniquely fun.

 
About the Technical Reviewers
Yusuf Pisan
../images/334805_2_En_BookFrontmatter_Figc_HTML.jpg
is an Associate Teaching Professor in the School of Computing & Software Systems Division at the University of Washington Bothell. Previously, he has worked at the University of Technology, Sydney, and has been a visiting professor at Harvey Mudd College, University of Southern California, Worcester Polytechnic Institute (WPI), and IT University of Copenhagen (ITU).

His research interests include enabling technologies for computer games, the design of virtual environments that support collaborative work, and computer science education. He founded the Australasian Conference on Interactive Entertainment conference series and helped foster the Australian games community. His list of publications can be found at Google Scholar.

Yusuf has a Ph.D. in Artificial Intelligence from Northwestern University. Before moving to Seattle in 2017, Yusuf lived in the Chicago area for 10 years and Sydney for 20 years.

For more information, see https://pisanorg.github.io/yusuf/.

 
Yogendra Sharma
../images/334805_2_En_BookFrontmatter_Figd_HTML.jpg
is a developer with experience in the architecture, design, and development of scalable and distributed applications, with a core interest in Microservices and Spring. He currently works as an IoT and Cloud Architect at Intelizign Engineering Services Pvt. Ltd., Pune.

He also has hands-on experience in technologies such as AWS, IoT, Python, J2SE, J2EE, NodeJS, VueJs, Angular, MongoDB, and Docker.

He constantly explores technical novelties, and he is open-minded and eager to learn about new technologies and frameworks. He has reviewed several books and video courses published by Packt.

 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.118.198