Saturday 25 April 2015

2D Vector Tutorial - Part 2, Vector Normalisation

In Part 1 we looked at what a vector was, and its composition in relation to 2D games.

Here in Part 2 we will look at normalising a vector. Don't worry yet if you don't know how we are going to use it later - we will get to that.


Assumptions:

This tutorial assumes you have read through part one and are familiar with that and the underlying concepts.


What is Normalising?

Simply put, Normalising is making the Magnitude of your vector equal 1 unit in length. 

This on its own isn't of much use in a 2D game as we still need the other components (the X and Y lengths), which will change in value if we change the magnitude.

Happily though, we can use what we learned in part one to find these values.


How to Normalise a Vector

There are a few ways to normalise a vector, but here we are just going to focus on one which uses data we already have.

In part one, we had a vector with the following properties (fig 1):


Origin point on X axis (Ox) = 100
Origin point on Y axis (Oy) = 100
End point on X axis (Ex) = 50
End point on Y axis (Ey) = 50


X = -50
Y = -50

Magnitude = 70.7107 rounded to 4 places


fig 1


Important Note : In the example above, we rounded up the Magnitude to four decimal places. However, to be as accurate as possible we dont really want to do that in a game if we can avoid it. In reality we would have the vector components as floating point values and we wouldnt round them up at all.

So, without rounding, the Magnitude of our original vector should be 70.71067812 - which is what we will use from now on.

So let's normalise that vector.

To do so, we simply divide each axis component length by the magnitude of the vector. We shall call these Nx and Ny, which gives us:

Nx = X / Magnitude
Ny = Y / Magnitude

Substituting in actual values from our vector:

Nx = -50 / 70.71067812 , which results in Nx = -0.7071067812
Ny = -50 / 70.71067812,  which results in Ny = -0.7071067812
Nmagnitude = 1

We dont have to, but if we use pythagoras theorem again using the Nx and Ny values we have just calculated, the magnitude will be 1. Try it.

So, normalised vectors are just scaled down versions of the original vector (fig 2).

fig 2

You can see that our vector is still moving upwards and leftwards in the same proportions as the original.

If we multiplied the Nx and NY values above by the original (non rounded) vector magnitude, we would get our original vector's X and Y figures.


Why do we need to normalise vectors?

As vectors can be different lengths and directions, to simplify later calculations it is much easier to normalise the vectors. Normalised vectors are used in calculating dot products and make finding angles pretty easy.






No comments:

Post a Comment