Game Physics Cookbook - Gabor Szauer - E-Book

Game Physics Cookbook E-Book

Gabor Szauer

0,0
32,39 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

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:

EPUB
MOBI

Seitenzahl: 552

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Game Physics Cookbook
Credits
About the Author
Acknowledgements
About the Reviewer
Acknowledgements
www.PacktPub.com
eBooks, discount offers, and more
Why Subscribe?
Customer Feedback
Preface
What this book covers
What you need for this book
Who this book is for
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Vectors
Introduction
Vector definition
Getting ready
How to do it…
How it works…
There's more…
The W component
Component-wise operations
Getting ready
How to do it…
How it works…
Addition
Subtraction
Multiplication (Vector and Scalar)
Comparison
There's more…
Dot product
How to do it…
How it works…
There's more…
Geometric definition
Magnitude
Getting ready
How to do it…
How it works…
There's more…
Normalizing
Getting ready
How to do it…
How it works…
Cross product
Getting ready
How to do it…
How it works…
Angles
Getting ready
How to do it…
How it works…
There's more…
Radians and degrees
Projection
Getting ready
How to do it…
How it works…
Reflection
Getting ready
How to do it…
How it works…
2. Matrices
Introduction
Matrix definition
Getting ready
How to do it…
How it works…
Transpose
Getting ready
How to do it…
How it works…
Multiplication
Getting ready
How to do it…
How it works…
Identity matrix
Getting ready
How to do it…
How it works…
Determinant of a 2x2 matrix
How to do it…
How it works…
Matrix of minors
Getting ready
How to do it…
How it works…
Minor of a 2x2 matrix
Minor of a 3x3 matrix
Cofactor
Getting ready
How to do it…
How it works…
Determinant of a 3x3 matrix
Getting ready
How to do it…
How it works…
Operations on a 4x4 matrix
Getting ready
How to do it…
How it works…
Adjugate matrix
Getting ready
How to do it…
How it works…
Matrix inverse
Getting ready
How to do it…
How it works…
There's more…
Expanding the inverse
3. Matrix Transformations
Introduction
Matrix majors
Translation
Getting Ready
How to do it…
How it works…
Scaling
Getting ready
How to do it…
How it works…
How rotations work
Getting ready
How to do it…
How it works…
Rotation matrices
Getting ready
How to do it…
How it works…
X-Basis vector
Y-Basis vector
Z-Basis vector
There's more…
X and Y rotation
Axis angle rotation
Getting ready
How to do it…
How it works…
Vector matrix multiplication
Getting ready
How to do it…
How it works…
Transform matrix
Getting ready
How to do it…
How it works…
View matrix
Getting ready
How to do it…
How it works…
Projection matrix
Getting ready
How to do it…
How it works…
4. 2D Primitive Shapes
Introduction
2D points
Getting ready
How to do it…
How it works…
2D lines
Getting ready
How to do it…
How it works…
Circle
Getting ready
How to do it…
How it works…
Rectangle
Getting ready
How to do it…
How it works…
Oriented rectangle
Getting ready
How to do it…
How it works…
Point containment
Getting ready
How to do it…
How it works…
Point on a line
Point in a circle
Point in a rectangle
Point in an oriented rectangle
Line intersection
Getting ready
How to do it…
How it works…
Line circle
Line rectangle
Line oriented rectangle
5. 2D Collisions
Introduction
Circle to circle
Getting ready
How to do it…
How it works…
Circle to rectangle
Getting ready
How to do it…
How it works…
There's more…
Circle to oriented rectangle
Getting ready
How to do it…
How it works…
Rectangle to rectangle
Getting ready
How to do it…
How it works…
Separating Axis Theorem
Getting ready
How to do it…
How it works…
There's more…
Determining which axis to test
Rectangle to oriented rectangle
Getting ready
How to do it…
How it works…
Oriented rectangle to oriented rectangle
Getting ready
How to do it…
How it works…
6. 2D Optimizations
Introduction
Containing circle
Getting ready
How to do it…
How it works…
Containing rectangle
Getting ready
How to do it…
How it works…
Simple and complex shapes
Getting ready
How to do it…
How it works…
Quad tree
Getting ready
How to do it…
How it works…
Broad phase collisions
Getting ready
How to do it…
How it works…
7. 3D Primitive Shapes
Introduction
Point
Getting ready
How to do it…
How it works…
Line segment
Getting ready
How to do it…
How it works…
Ray
Getting ready
How to do it…
How it works…
Sphere
Getting ready
How to do it…
How it works…
Axis Aligned Bounding Box
Getting ready
How to do it
How it works
Oriented Bounding Box
Getting ready
How to do it
How it works
Plane
Getting ready
How to do it
How it works
Triangle
Getting ready
How to do it
How it works
8. 3D Point Tests
Introduction
Point and sphere
Getting ready
How to do it…
How it works…
Point and AABB
Getting ready
How to do it…
How it works…
Point and Oriented Bounding Box
Getting ready
How to do it…
How it works…
Point and plane
Getting ready
How to do it…
How it works…
Point and line
Getting ready
How to do it…
How it works…
Point and ray
Getting ready
How to do it…
How it works…
9. 3D Shape Intersections
Introduction
Sphere-to-sphere
Getting ready
How to do it…
How it works…
Sphere-to-AABB
Getting ready
How to do it…
How it works…
Sphere-to-OBB
Getting ready
How to do it…
How it works…
Sphere-to-plane
Getting ready
How to do it…
How it works…
AABB-to-AABB
Getting ready
How to do it…
How it works…
AABB-to-OBB
Getting ready
How to do it…
How it works…
AABB-to-plane
Getting ready
How to do it…
How it works…
OBB-to-OBB
Getting ready
How to do it…
How it works…
OBB-to-plane
Getting ready
How to do it…
How it works…
Plane-to-plane
Getting ready
How to do it…
How it works…
10. 3D Line Intersections
Introduction
Raycast Sphere
Getting ready
How to do it…
How it works…
Raycast Axis Aligned Bounding Box
Getting ready
How to do it…
How it works…
Raycast Oriented Bounding Box
Getting ready
How to do it…
How it works…
Raycast plane
Getting ready
How to do it…
How it works…
Linetest Sphere
Getting ready
How to do it…
How it works…
Linetest Axis Aligned Bounding Box
Getting ready
How to do it…
How it works…
Linetest Oriented Bounding Box
Getting ready
How to do it…
How it works…
Linetest Plane
Getting ready
How to do it…
How it works…
11. Triangles and Meshes
Introduction
Point in triangle
Getting ready
How to do it…
How it works…
Closest point triangle
Getting ready
How to do it…
How it works…
Triangle to sphere
Getting ready
How to do it…
How it works…
Triangle to Axis Aligned Bounding Box
Getting ready
How to do it…
How it works…
Triangle to Oriented Bounding Box
Getting ready
How to do it…
How it works…
Triangle to plane
Getting ready
How to do it…
How it works…
Triangle to triangle
Getting ready
How to do it…
How it works…
Robustness of the Separating Axis Theorem
Getting ready
How to do it…
How it works…
Raycast Triangle
Getting ready
How to do it…
How it works…
Linetest Triangle
Getting ready
How to do it…
How it works…
Mesh object
Getting ready
How to do it…
How it works…
Mesh optimization
Getting ready
How to do it…
How it works…
Mesh operations
Getting ready
How to do it…
How it works…
There's more…
12. Models and Scenes
Introduction
The Model object
Getting ready
How to do it…
How it works…
Operations on models
Getting ready
How to do it…
How it works…
The Scene object
Getting ready
How to do it…
How it works…
There's more
Operations on the scene
Getting ready
How to do it…
How it works…
The Octree object
Getting ready
How to do it…
How it works…
Octree contents
Getting ready
How to do it…
How it works…
Operations on the Octree
Getting ready
How to do it…
How it works…
Octree scene integration
Getting ready
How to do it…
How it works…
13. Camera and Frustum
Introduction
Camera object
Getting ready
How to do it…
How it works…
Camera controls
Getting ready
How to do it…
How it works…
Frustum object
Getting ready
How to do it…
How it works…
Frustum from matrix
Getting ready
How to do it…
How it works…
Sphere in frustum
Getting ready
How to do it…
How it works…
Bounding Box in frustum
Getting ready
How to do it…
How it works…
Octree culling
Getting Ready
How to do it…
How it works…
Picking
Getting ready
How to do it…
How it works…
There's more…
14. Constraint Solving
Introduction
Framework introduction
Getting ready
How to do it…
How it works…
There's more…
Raycast sphere
Getting ready
How to do it…
How it works…
Raycast Bounding Box
Getting ready
How to do it…
How it works…
Raycast plane and triangle
Getting ready
How to do it…
How it works…
Physics system
Getting ready
How to do it…
How it works…
Integrating particles
Getting ready
How to do it…
How it works…
There's more…
Solving constraints
Getting ready
How to do it…
How it works…
Verlet Integration
Getting ready
How to do it…
How it works…
15. Manifolds and Impulses
Introduction
Manifold for spheres
Getting ready
How to do it…
How it works…
Manifold for boxes
Getting ready
How to do it…
How it works…
There's more…
Duplicate points
Rigidbody Modifications
Getting ready
How to do it…
How it works…
Linear Velocity
Getting ready
How to do it...
How it works...
Linear Impulse
Getting ready
How to do it...
How it works...
Linear Impulse
Friction
There's more...
Physics System Update
Getting ready
How to do it...
How it works...
Angular Velocity
Angular Velocity and Acceleration
Tangential Acceleration
Centripetal Acceleration
Torque
Inertia Tensor
Getting ready
How to do it...
How it works...
There's more...
Tensors
Angular Impulse
Getting ready
How to do it...
How it works...
There's more...
Non-linear projection
16. Springs and Joints
Introduction
Particle Modifications
Getting ready
How to do it…
How it works…
Springs
Getting ready
How to do it…
How it works…
Cloth
Getting ready
How to do it…
How it works…
Physics System Modification
Getting ready
How to do it…
How it works…
Joints
Getting ready
How to do it…
How it works…
There's more…
A. Advanced Topics
Introduction
Generic collisions
Minkowski Sum
Gilbert Johnson Keerthi (GJK)
Expanding Polytope Algorithm (EPA)
Stability improvements
Arbiters
Accumulated impulse
Springs
Collision resolution
Softbody objects
Open source physics engines
Box2D Lite
Box2D
Dyn4j
Bullet
ODE
JigLib
React 3D
Qu3e
Cyclone Physics
Books
Online resources
Summary
Index

Game Physics Cookbook

Game Physics Cookbook

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

Credits

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

About the Author

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.

Acknowledgements

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.

About the Reviewer

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.

Acknowledgements

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.

www.PacktPub.com

eBooks, discount offers, and more

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.

Why Subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Customer Feedback

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

Preface

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.

What this book covers

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.

What you need for this book

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.

Who this book is for

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.

Sections

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:

Getting ready

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.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

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: "We can include other contexts through the use of the include directive."

A block of code is set as follows:

#ifndef _H_MATH_VECTORS_ #define _H_MATH_VECTORS_ // Structure definitions // Method declarations #endif

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"

Note

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)

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

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

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

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:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

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!

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

Questions

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.

Chapter 1. Vectors

In this chapter, we will cover the following vector operations:

AdditionSubtractionMultiplicationScalar MultiplicationCross ProductDot ProductMagnitudeDistanceNormalizationAngleProjectionReflection

Introduction

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.

Note

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.

Dot product

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:

If the dot product is positive, the vectors are pointing in the same directionIf the dot product is negative, the vectors point in opposing directionsIf the dot product is 0, the vectors are perpendicular

How to do it…

Follow these steps to implement the dot product for two and three dimensional vectors:

Add the declaration for the dot product to vectors.h:
float Dot(const vec2& l, const vec2& r); float Dot(const vec3& l, const vec3& r);
Add the implementation for the dot product to vector.cpp:
float Dot(const vec2& l, const vec2& r) { return l.x * r.x + l.y * r.y; } float Dot(const vec3& l, const vec3& r) { return l.x * r.x + l.y * r.y + l.z * r.z; }

How it works…

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.

There's more…

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.

Geometric definition

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.

Projection

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