Reflection
One of the most important concepts in physics for games is collision response and how to react to a collision occurring. More often than not this involves one of the colliding objects bouncing off the other one. We can achieve the bounding through vector reflection. Reflection is also heavily used in many areas of game development, such as graphics programming, to find the color intensity of a fragment.
Given vector and normal
, we want to find a vector
that is
reflected around
:
![Reflection](https://static.packt-cdn.com/products/9781787123663/graphics/graphics/B05887_1_092.jpg)
The reflected vector can be found with the following formula:
![Reflection](https://static.packt-cdn.com/products/9781787123663/graphics/graphics/B05887_1_093.jpg)
Keep in mind, in the preceding equation, is a unit length vector. This means that the
part of the equation actually projects
onto
. If
was a non-normalized vector, the preceding equation would be written as follows:
![Reflection](https://static.packt-cdn.com/products/9781787123663/graphics/graphics/B05887_1_095.jpg)
Getting ready
Implementing the preceding formula is going to look a little different, this is because we only overloaded the vector scalar multiplication with the scalar being on the right side of the equation. We're going to implement the function assuming is already normalized.
How to do it…
Follow these steps to implement a function which will reflect both two and three dimensional vectors.
- Add the declaration of the reflection function to
vectors.h
:vec2 Reflection(const vec2& vec, const vec2& normal); vec3 Reflection(const vec3& vec, const vec3& normal);
- Add the implementation of the reflection function to
vectors.cpp
:vec2 Reflection(const vec2& vec,const vec2& normal) { float d = Dot(vec, normal); return sourceVector - normal * (d * 2.0f ); } vec3 Reflection(const vec3& vec, const vec3& normal) { float d = Dot(vec, normal); return sourceVector - normal * (d * 2.0f); }
How it works…
Given and
, we're going to find
, which is the reflection of
around
:
![How it works…](https://static.packt-cdn.com/products/9781787123663/graphics/graphics/B05887_1_097.jpg)
First, we project onto
, this operation will yield a vector along
that has the length of
:
![How it works…](https://static.packt-cdn.com/products/9781787123663/graphics/graphics/B05887_1_098.jpg)
We want to find the reflected vector . The following figure shows
in two places, remember it doesn't matter where you draw a vector as long as its components are the same:
![How it works…](https://static.packt-cdn.com/products/9781787123663/graphics/graphics/B05887_1_099.jpg)
Looking at the preceding figure, we can tell that subtracting from
will result in
:
![How it works…](https://static.packt-cdn.com/products/9781787123663/graphics/graphics/B05887_1_101.jpg)
This is how we get to the final formula, .