32,39 €
Physics is really important for game programmers who want to add realism and functionality to their games. Collision detection in particular is a problem that affects all game developers, regardless of the platform, engine, or toolkit they use.
This book will teach you the concepts and formulas behind collision detection. You will also be taught how to build a simple physics engine, where Rigid Body physics is the main focus, and learn about intersection algorithms for primitive shapes.
You’ll begin by building a strong foundation in mathematics that will be used throughout the book. We’ll guide you through implementing 2D and 3D primitives and show you how to perform effective collision tests for them. We then pivot to one of the harder areas of game development—collision detection and resolution.
Further on, you will learn what a Physics engine is, how to set up a game window, and how to implement rendering. We’ll explore advanced physics topics such as constraint solving. You’ll also find out how to implement a rudimentary physics engine, which you can use to build an Angry Birds type of game or a more advanced game.
By the end of the book, you will have implemented all primitive and some advanced collision tests, and you will be able to read on geometry and linear Algebra formulas to take forward to your own games!
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 552
Veröffentlichungsjahr: 2017
Copyright © 2017 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 author 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 2017
Production reference: 1200317
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78712-366-3
www.packtpub.com
Author
Gabor Szauer
Reviewers
Francesco Sapio
Commissioning Editor
Ashwin Nair
Acquisition Editor
Divya Poojari
Content Development Editor
Onkar Wani
Technical Editor
Rashil Shah
Copy Editors
Safis Editing
Shaila Kusanale
Project Coordinator
Devanshi Doshi
Proofreader
Safis Editing
Indexer
Francy Puthiry
Graphics
Abhinash Sahu
Production Coordinator
Aparna Bhagat
Cover Work
Aparna Bhagat
Gabor Szauer graduated from Full Sail University with a bachelor's degree in game development. He has been making video games professionally for over 6 years. He has worked on games for the Nintendo 3DS, Xbox 360, browser-based games, and mobile games.
In his free time Gabor makes video games, researches video game-related technologies, and likes to design and construct furniture. Gabor currently resides in San Francisco, working in the mobile game industry.
I would like to thank my mom and dad, Gabriella and János. Without your constant love and support this book would not be possible.
I also want to thank my wife Lisa Jennifer Gordon who not only managed to put up with me through the process of writing this book, but helped create many of the illustrations in the book as well.
Finally, I want to thank my brother Martin, without his curiosity for programming the first draft of this book would not have been written.
Francesco Sapio obtained his Computer Science and Control Engineering degree from Sapienza University of Rome, Italy, with a couple of semesters in advance, scoring summa cum laude. He is currently studying a Master of Science in Engineering in Artificial Intelligence and Robotics at the same university.
He is a Unity3D and Unreal expert, a skilled game designer, and an experienced user of the major graphics programs. He developed Gea2, formerly Game@School (Sapienza University of Rome), an educational game for high school students to learn the concepts of physics, and Sticker Book (series) (Dataware Games), a cross-platform series of games for kids. In addition, he worked as a consultant for the (successfully funded by Kickstarter) game Prosperity – Italy 1434 (Entertainment Game Apps, Inc.), and for the open online collaborative ideation system titled Innovoice (Sapienza University of Rome). Moreover, he has been involved in different research projects such as Belief-Driven-Pathfinding (Sapienza University of Rome), a new technique for pathfinding in videogames that was presented as a paper at the DiGRA-FDG Conference 2016; and perfekt.ID (Royal Melbourne Institute of Technology), which included developing a recommendation system for games.
He is an active writer on the topic of game development. Recently, he authored the book Getting Started with Unity 5.x 2D Game Development (Packt Publishing) which takes your hand and guides you through the amazing journey of game development, the successful Unity UI Cookbook (Packt Publishing), which has been translated into other languages and teaches readers how to develop exciting and practical user interfaces for games within Unity, and a short e-guide What do you need to know about Unity (Packt Publishing). In addition, he co-authored the book Unity 5.x 2D Game Development Blueprints (Packt Publishing). Furthermore, he has also been a reviewer for the following books: Mastering Unity 5.x (Packt Publishing), Unity 5.x by Example (Packt Publishing), and Unity Game Development Scripting (Packt Publishing).
Francesco is also a musician and a composer, especially of soundtracks for short films and video games. For several years, he worked as an actor and dancer, where he was a guest of honor at the theatre Brancaccio in Rome. In addition, he is a very active person, having volunteered as a children's entertainer at the Associazione Culturale Torraccia in Rome.
Finally, Francesco loves math, philosophy, logic, and puzzle solving, but most of all, creating video games — thanks to his passion for game designing and programming.
You can find him at www.francescosapio.com.
I'm deeply thankful to my parents for their infinite patience, enthusiasm, and support throughout my life. Moreover, I'm thankful to the rest of my family, in particular to my grandparents, since they have always encouraged me to do better in my life with the Latin expressions "Ad maiora" and "Per aspera ad astra".
Finally, a huge thanks to all the special people around me whom I love, in particular to my girlfriend; I'm grateful for all of your help in everything. I do love you.
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 <[email protected]> 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://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Thank you for purchasing this Packt book. We take our commitment to improving our content and products to meet your needs seriously—that's why your feedback is so valuable. Whatever your feelings about your purchase, please consider leaving a review on this book's Amazon page. Not only will this help us, more importantly it will also help others in the community to make an informed decision about the resources that they invest in to learn.
You can also review for us on a regular basis by joining our reviewers' club. If you're interested in joining, or would like to learn more about the benefits we offer, please contact us: <[email protected]>.
At some point in your game development career, you might need to build a physics engine, modify the source code of an existing physics engine, or even just model some interaction using an existing physics engine. Each of these tasks is a real challenge. Knowing how a physics engine is implemented under the hood will make all of these scenarios a lot simpler.
Building a physics engine from scratch might seem like a large, complex and confusing project, but it doesn't have to be. Behind every physics engine are the same three core components: a solid math library, accurate intersection testing, and usually impulse-based collision resolution. The collision resolution does not have to use an impulse-based solver; other resolution strategies exist as well.
This book covers the three core components of a physics engine in great detail. By the end of the book you will have implemented particle-based physics, rigid body physics, and even soft body physics through cloth simulation. This cookbook aims to break the components of a physics engine down into bite-sized, independent recipes.
Chapter 1, Vectors, covers vector math using 2D and 3D vectors. Vectors will be heavily used throughout the book, so having a solid understanding of the math behind vectors is essential.
Chapter 2, Matrices, covers the basics of 2D, 3D, and 4D matrices. Operations such as matrix multiplication and inversion are covered. This chapter is an introduction to the implementation matrices in C++.
Chapter 3, Matrix Transformations, covers applying matrices to games. This chapter builds upon the understanding of vectors and matrices built up in the previous chapters to explain how matrices and vectors can be used to represent transformations in 3D space.
Chapter 4, 2D Primitive Shapes, covers common 2D shapes games may need. This chapter provides practical definitions and implementations of common 2D primitives.
Chapter 5, 2D Collisions, covers testing the 2D shapes defined in the last chapter for intersection. This chapter covers the fundamental concepts of intersection testing in 2D, which later chapters will expand into 3D.
Chapter 6, 2D Optimizations, covers speeding up the intersection tests written in the last chapter. Once hundreds or even thousands of objects are colliding, brute force collision detection will no longer work in real time. The topics covered in this chapter are vital for keeping collision detection running in real time, even with a large number of objects.
Chapter 7, 3D Primitive Shapes, covers the common 3D shapes games may need. This chapter provides the definition of the geometric primitives we will later build upon to create a working 3D physics engine.
Chapter 8, 3D Point Tests, covers nearest point and containment tests in a 3D environment. This chapter covers finding the closest point on the surface of a 3D primitive to a given point and provides containment tests for the 3D primitives previously covered.
Chapter 9, 3D Shape Intersections, covers testing all of the 3D primitive shapes for intersection. This chapter expands many of the 2D intersection tests covered previously in the book into 3D space. The chapter also provides additional insight into optimizing intersection tests in 3D space.
Chapter 10, 3D Line Intersections, covers testing the intersection of a line and any 3D primitive, as well as raycasting against any 3D primitive. Ray casting is perhaps one of the most versatile intersection tests. We will use ray casting in later chapters to avoid the common problem of tunneling.
Chapter 11, Triangles and Meshes, covers a new primitive, the triangle, and how to use triangles to represent a mesh. In a 3D game world, objects are often represented by complex meshes rather than primitive 3D shapes. This chapter presents the most straightforward way of representing these complex meshes in the context of a physics engine.
Chapter 12, Models and Scenes, covers adding a transformation to a mesh, as well as using a hierarchy of meshes to represent a scene. Games often reuse the same mesh transformed into a different space. This chapter defines a model, which is a mesh with some transformation. The chapter also covers multiple models in a scene.
Chapter 13, Camera and Frustum, covers the frustum primitive and building a camera out of matrices. The focus of this chapter is to build an easy to use camera which can be used to view any 3D scene. Each camera will have a frustum primitive attached. The attached frustum primitive can optimize render times by culling unseen objects.
Chapter 14, Constraint Solving, covers a basic introduction to physics. This chapter introduces particle physics and world space constraints for particles. In this chapter, the word constraint refers to an immovable object in the physics simulation.
Chapter 15, Manifolds and Impulses, extends the particle physics engine built in the last chapter by defining a rigid body object, which unlike a particle has some volume. Impulse-based collision resolution is also covered in this chapter.
Chapter 16, Springs and Joints, creates springs and simple joint constraints for springs. Using springs and particles, this chapter covers the basic concept of soft body physics. The chapter focuses on implementing 3D cloth using springs and particles.
Appendix, Advanced Topics, covers issues this book did not have the scope to address. Building a physics engine is a huge undertaking. While this book built a basic physics engine, there are many topics that fell outside the scope of this book. This chapter provides guidance, references, and resources to help the reader explore these advanced topics further.
Working knowledge of the C++ language is required for this book, as the book is not a tutorial about programming. Having a basic understanding of calculus and linear algebra will be useful, but is not required. You will need a Windows PC (preferably with Windows 7 or higher) with Microsoft Visual Studio 2015 installed on it.
This book is for beginner to intermediate game developers. You don't need to have a formal education in games—you can be a hobbyist or indie developer who started making games with Unity 3D.
In this book, you will find several headings that appear frequently (Getting ready, How to do it…, How it works…, There's more…, and See also).
To give clear instructions on how to complete a recipe, we use these sections as follows:
This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
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: "We can include other contexts through the use of the include directive."
A block of code is set as follows:
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: "Under the Application divider you will find the code"
Creating a Win32 window with an active OpenGL Context is outside the scope of this book. For a better understanding of how Win32 code works with OpenGL read: https://www.khronos.org/opengl/wiki/Creating_an_OpenGL_Context_(WGL)
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 <[email protected]>, 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.
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.
You can download the example code files for this book from your account at http://www.packtpub.com. 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.
You can download the code files by following these steps:
You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Game-Physics-Cookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
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 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 <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
In this chapter, we will cover the following vector operations:
Throughout this book we are going to explore the mathematical concepts required to detect and react to intersections in a 3D environment. In order to achieve robust collision detection and build realistic reactions, we will need a strong understanding of the math required. The most important mathematical concepts in physics are Vectors and Matrices.
Physics and collisions rely heavily on Linear Algebra. The math involved may sound complicated at first, but it can be broken down into simple steps. The recipes in this chapter will explain the properties of vectors using math formulas. Each recipe will also contain a visual guide. Every formula will also have an accompanying code sample.
This chapter does not assume you have any advanced math knowledge. I try to cover everything needed to understand the formulas presented. If you find yourself falling behind, Khan Academy covers the basic concepts of linear algebra at: www.khanacademy.org/math/linear-algebra.
The dot product, sometimes referred to as scalar product or inner product between two vectors, returns a scalar value. It's written as a dot between two vectors, . The formula for the dot product is defined as follows:
The sigma symbol means sum (add) everything up that follows. The number on top of the sigma is the upper limit; the variable on the bottom is the lower limit. If n and i is 0, the subscripts 0, 1, and 2 are processed. Without using the sigma symbol, the preceding equation would look like this:
The resulting scalar represents the directional relation of the vectors. That is, represents how much is pointing in the direction of . Using the dot product we can tell if two vectors are pointing in the same direction or not following these rules:
Follow these steps to implement the dot product for two and three dimensional vectors:
Given the formula and the code for the dot product, let's see an example of what we could use it for. Assume we have a spaceship S. We know its forward vector, and a vector that points to its right, :
We also have an enemy ship E, and a vector that points from our ship S to the enemy ship E, vector :
How can we tell if the the ship S needs to turn left or right to face the enemy ship E?
We need to take the dot product of and . If the result of the dot product is positive, the ship needs to turn right. If the result of the dot product is negative, the ship needs to turn to the left. If the result of the dot product is 0, the ship does not need to turn.
Our definition of the dot product is fairly abstract. We know that the dot product gives us some information as to the angle between the two vectors, and . We can use the dot product to find the exact angle between these two vectors. The key to this is an alternate definition of the dot product.
Given the vectors and , the geometric definition of the dot product is the length of multiplied by the length of multiplied by the cosine of the angle between them:
The || operator in the above equation means length and will be covered in the next section. We will cover the geometric definition and other properties of the dot product later in this chapter.
Sometimes it's useful to decompose a vector into parallel and perpendicular components with respect to another vector. Projecting onto will give us the length of in the direction of . This projection decomposes into its parallel component with respect to . Once we know the parallel component of , we can use it to get the