Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Game Physics Cookbook

You're reading from   Game Physics Cookbook Discover over 100 easy-to-follow recipes to help you implement efficient game physics and collision detection in your games

Arrow left icon
Product type Paperback
Published in Mar 2017
Publisher Packt
ISBN-13 9781787123663
Length 480 pages
Edition 1st Edition
Languages
Tools
Concepts
Arrow right icon
Author (1):
Arrow left icon
Gabor Szauer Gabor Szauer
Author Profile Icon Gabor Szauer
Gabor Szauer
Arrow right icon
View More author details
Toc

Table of Contents (19) Chapters Close

Preface 1. Vectors FREE CHAPTER 2. Matrices 3. Matrix Transformations 4. 2D Primitive Shapes 5. 2D Collisions 6. 2D Optimizations 7. 3D Primitive Shapes 8. 3D Point Tests 9. 3D Shape Intersections 10. 3D Line Intersections 11. Triangles and Meshes 12. Models and Scenes 13. Camera and Frustum 14. Constraint Solving 15. Manifolds and Impulses 16. Springs and Joints A. Advanced Topics Index

Component-wise operations

Given two vectors, there are several component-wise operations we can perform. These operations will operate on each component of the vector and yield a new vector.

You can add two vectors component wise. Given two n-dimensional vectors Component-wise operations and Component-wise operations, addition is defined as follows:

Component-wise operations

You can also subtract two vectors component wise. Given two n-dimensional vectors Component-wise operationsand Component-wise operations, subtraction is defined as follows:

Component-wise operations

Multiplying two vectors can also be done component wise. There are other ways to multiply two vectors; the dot product or cross product. Both of these alternate methods will be covered later in this chapter. Given two n-dimensional vectors Component-wise operations and Component-wise operations, multiplication is defined as follows:

Component-wise operations

In addition to multiplying two vectors, you can also multiply a vector by a scalar. In this context, a scalar is any real number. Given vector Component-wise operations and scalar S, scalar multiplication is defined as follows:

Component-wise operations

Finally, we can check for vector equality by comparing each component of the vectors being tested. Two vectors are the same only if all of their components are equal.

Getting ready

We're going to implement all of the preceding component-wise operations by overloading the appropriate C++ operators. All of the operators presented in this section can be overloaded in C# as well. In languages that do not support operator overloading, you will have to make these into regular functions.

How to do it…

Follow these steps to override common operators for the vector class. This will make working with vectors feel more intuitive:

  1. In vectors.h, add the following function declarations:
    vec2 operator+(const vec2& l, const vec2& r);
    vec3 operator+(const vec3& l, const vec3& r);
    vec2 operator-(const vec2& l, const vec2& r);
    vec3 operator-(const vec3& l, const vec3& r);
    vec2 operator*(const vec2& l, const vec2& r);
    vec3 operator*(const vec3& l, const vec3& r);
    vec2 operator*(const vec2& l, float r);
    vec3 operator*(const vec3& l, float r);
    bool operator==(const vec2& l, const vec2& r);
    bool operator==(const vec3& l, const vec3& r);
    bool operator!=(const vec2& l, const vec2& r);
    bool operator!=(const vec3& l, const vec3& r);
  2. Create a new C++ source file, vectors.cpp. Include the following headers in the new file:
    #include "vectors.h"
    #include <cmath>
    #include <cfloat>
  3. Add a macro for comparing floating point numbers to vectors.cpp:
    #define CMP(x, y)                    \
        (fabsf((x)–(y)) <= FLT_EPSILON * \
          fmaxf(1.0f,                    \
          fmaxf(fabsf(x), fabsf(y)))     \
       )
  4. Add the implementation of vector addition to the vectors.cpp file:
    vec2 operator+(const vec2& l, const vec2& r) {
       return { l.x + r.x, l.y + r.y };
    }
    
    vec3 operator+(const vec3& l, const vec3& r) {
       return { l.x + r.x, l.y + r.y, l.z + r.z };
    }
  5. Add the implementation of vector subtraction to the vectors.cpp file:
    vec2 operator-(const vec2& l, const vec2& r) {
       return { l.x - r.x, l.y - r.y };
    }
    
    vec3 operator-(const vec3& l, const vec3& r) {
       return { l.x - r.x, l.y - r.y, l.z - r.z };
    }
  6. Add the implementation for vector multiplication to the vectors.cpp file:
    vec2 operator*(const vec2& l, const vec2& r) {
       return { l.x * r.x, l.y * r.y };
    }
    
    vec3 operator*(const vec3& l, const vec3& r) {
       return { l.x * r.x, l.y * r.y, l.z * r.z };
    }
  7. Add the implementation for scalar multiplication to the vectors.cpp file:
    vec2 operator*(const vec2& l, float r) {
       return { l.x * r, l.y * r };
    }
    
    vec3 operator*(const vec3& l, float r) {
       return { l.x * r, l.y * r, l.z * r };
    }
  8. Finally, add the implementation for vector equality to the vectors.cpp file. This is where the compare macro we created in step 3 comes in:
    bool operator==(const vec2& l, const vec2& r) { 
       return CMP(l.x, r.x) && CMP(l.y, r.y);
    }
    
    bool operator==(const vec3& l, const vec3& r) {
       return CMP(l.x, r.x) && CMP(l.y, r.y) && CMP(l.z, r.z);
    }
    
    bool operator!=(const vec2& l, const vec2& r) {
       return !(l == r);
    }
    
    bool operator!=(const vec3& l, const vec3& r) {
       return !(l == r);
    }

How it works…

What these components-wise operations are doing might not be obvious from the definitions and code provided alone. Let's explore the component-wise operations of vectors visually.

Addition

Every vector describes a series of displacements. For example, the vector (2, 3) means move two units in the positive X direction and three units in the positive Y direction. We add vectors by following the series of displacements that each vector represents. To visualize this, given vectors Addition and Addition, draw them so the head of Additiontouches the tail of Addition The result of the addition is a new vector spanning from the tail of Addition to the head of Addition:

Addition

Subtraction

Subtraction works the same way as addition. We have to follow the negative displacement of vector Subtraction starting from vector Subtraction. To visually subtract vectors Subtraction and Subtraction, draw Subtraction and Subtraction with their tails touching. The result of the subtraction is a vector spanning from the head of Subtraction to the head of Subtraction:

Subtraction

A more intuitive way to visualize subtraction might be to think of it as adding negative Subtraction toSubtraction, like so; Subtraction. If we represent the subtraction like this, visually we can follow the rules of addition:

Subtraction

In the above image, the vector Subtractionappears multiple times. This is to emphasize that the position of a vector does not matter. Both of the Subtraction vectors above represent the same displacement!

Multiplication (Vector and Scalar)

Multiplying a vector by a scalar will scale the vector. This is easy to see when we visualize the result of a multiplication. The scalar multiplication of a vector will result in a uniform scale, where all components of the vector are scaled by the same amount. Multiplying two vectors on the other hand results in a non-uniform scale. This just means that each component of the vector is scaled by the corresponding component of the other vector:

Multiplication (Vector and Scalar)

Comparison

Comparing vectors is a component-wise operation. If every component of each vector is the same, the vectors are equal. However, due to floating point error we can't compare floats directly. Instead, we must do an epsilon comparison. Epsilon tests commonly fall in one of two categories: absolute tolerance and relative tolerance:

#define ABSOLUTE(x, y) (fabsf((x)–(y)) <= FLT_EPSILON)
#define RELATIVE(x, y) \
(fabsf((x) – (y)) <= FLT_EPSILON * Max(fabsf(x), fabsf(y)))

The absolute tolerance test fails when the numbers being compared are large. The relative tolerance test fails when the numbers being compared are small. Because of this, we implemented a tolerance test with the CMP macro that combines the two. The logic behind the CMP macro is described by Christer Ericson at www.realtimecollisiondetection.net/pubs/Tolerances.

There's more…

It's desirable to make vectors easy to construct in code. We can achieve this by adding default constructors. Each vector should have two constructors: one that takes no arguments and one that takes a float for each component of the vector. We do not need a copy constructor or assignment operator as the vec2 and vec3 structures do not contain any dynamic memory or complex data. The pair of constructors for the vec2 structure will look like this:

vec2() : x(0.0f), y(0.0f) { }
vec2(float _x, float _y) : x(_x), y(_y) { }

The vec3 constructors will look similar, it adds an additional component. The constructors for the vec3 structure will look like this:

vec3() : x(0.0f), y(0.0f), z(0.0f) { }
vec3(float _x, float _y, float _z) : x(_x), y(_y), z(_z) { }
You have been reading a chapter from
Game Physics Cookbook
Published in: Mar 2017
Publisher: Packt
ISBN-13: 9781787123663
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime