===========================
vector-math-for-video-games
===========================


vector-math-for-video-games
===========================

.. _vector-math-for-video-games-1:

Vector Math for Video Games
===========================

.. image:: /attachment/clock.png :alt: analog clock vector example
:align: left

This document outlines the common vector math formulas and terminology
that is used for building 2d games.

When introducing a new concepts such as vectors, real life examples
assist in the learning process. A real life example of a vector is an
analog clock.

Analog clocks have hands to represent time. These hands could also
represent vectors. The hands much like vectors have different lengths or
magnitudes. The hands also have different directions just like the
vector.

| 

.. contents::

Terminology
-----------

**Vector**

A quantity possessing both magnitude and direction, represented by an
arrow the direction of which indicates the direction of the quantity and
the length of which is proportional to the magnitude. We can represent
vectors in our games to determine how to move entities in relation to
each other.

**Magnitude**

The size, extent, or length of a Vector.

**Direction**

The position or orientation of a vector. Vectors point into different
directions in space.

How do we use vectors in games?
-------------------------------

In video games, vectors are used to communicate relationships of objects
in space. They can be used to move objects like players or even
projectiles. Vector math might be tedious by hand, but multiple
iterations for a computer is non trivial. Computers are great at
iteration!

What is a vector?
-----------------

A vector consists of a point in space. This document assumes knowledge
about coordinates of points (x,y).

Math has developed many techniques to help describe objects in space. I
have documented the most common vector operations used when creating 2d
games.

Vector Operations for 2d games
------------------------------

In the following examples we will describe two vectors, v1 and v2.

Vector Addition

::


   Two vectors can be added together to form a new vector.  To perform vector addition, add the x and y coordinates.

   **Syntax:**   

    | ( v1.x + v2.x, v1.y + v2.y ) = ( v3.x, v3.y )
     
   **Example:**  

    |  v1 = (3,4)
    |  v2 = (4,6)
    |  v3 = (3+4,4+6) = (7,10)

   Vector addition is just addition of coordinate pairs. Simple right?



   Vector Subtraction

Two vectors can be subtracted from each other to form a new vector. To
perform vector subtraction, subtract the x and y coordinates.

**Syntax**

\| ( v1.x - v2.x, v1.y - v2.y ) = ( v3.x, v3.y )

**Example**

\| v1 = (4,2) \| v2 = (3,1) \| v3 = (4-3,2-1) = (1,1)

Vector addition is just subtraction of coordinate pairs. Again, simple
right?

Vector Magnitude

::


   A vectors magnitude (distance or length) can be calculated by the following formula:

   **Syntax**

    | Magnitude = sqrt( x^2 + y^2 )
     
   **Example**

    | v1 = (3,4)
    | Magnitude = sqrt( 3^2 + 4^2 ) = sqrt( 9 + 16 ) = sqrt( 25 ) = 5

   Magnitude doesn't always work out into a nice integer like 5 but the formula should make it easy to calculate.  


   Unit Vector

In mathematics, a unit vector can be computed for any vector. A unit
vector has the same direction as its parent but its length is 1 (the
unit length). The unit vector is very important in video games.

**Syntax:**

\| Unit Vector = ( x / magnitude, y / magnitude )

**Example:**

\| v1 = (3,4) \| Magnitude = 5 \| Unit Vector = (3/5, 4/5)

Scale a Vector \```````````````````\`

A vector can be multiplied or scaled by a number (scalar) to grow or
shrink its magnitude.

**Syntax**

\| Scaled Vector = ( x \* num, y \* num )

**Example**

\| number or scaler = 3 \| v1 = (3,4) \| Scaled Vector = (3\ *3,4*\ 3) =
(9,12)

Python Vector Class Object
--------------------------

*vector.py*

.. code-block:: python :linenos:

from math import sqrt

class Vector( object ): ““” complete 2d vector class.

::

   __slots__
     prevent a dict from being created when adding attributes to a class.

   reference
     http://docs.python.org/reference/datamodel.html#slots
   """

   __slots__ = ('x','y')


   def __init__(self, x, y):
       self.x = x
       self.y = y

   def getLength( self ):
       '''return the vectors magnitude (distance or length)'''
       return sqrt( self.x ** 2 + self.y ** 2 )

   def _setLength( self, val ):
       '''set the vectors magnitude and alter its x and y'''
       l = self.getLength()
       self.x *= val / l
       self.y *= val / l

   length = property(
       getLength, 
       _setLength, 
       None, "Gets or Sets vector length"
   )

   def scale( self, val ):
       '''Scale the vector (grow or shrink)'''
       return Vector( self.x * val, self.y * val )

   def unit( self ):
       return Vector( self.x / self.length, self.y / self.length)

   def __sub__( self, v ):
       return Vector( self.x - v.x, self.y - v.y )

   def __add__( self, v ):
       return Vector( v.x + self.x, v.y + self.y )

   def __str__( self ):
       return '(' + str(self.x) + ', ' + str(self.y) + ')'

   # Unary Operations

   def __abs__( self ):
       return Vector( abs(self.x), abs(self.y) )
