Sunday, November 6, 2011

Using Vector Mathematics, Vector addition and subtraction

3D Math in games is largely based on Vector Mathematics. If you're unfamiliar with this term, please read up on 'Vectorsbefore continuing.

If you're programming in C++, do not confuse vectors used for 3D math with the vector container used in the standard template library (STL).

In this post we'll talk about 3D vectors, 2D vector math is pretty much identical, just lacking calculations done in one of the dimensions. If you understand 3D vectors then you'll have no trouble understanding 2D vectors.

Vectors are defined by three components: x, y, and z. These components usually define either a position, direction, or velocity along the x, y, and z axes.



Vector Addition and Subtraction
Adding and subtracting vectors is just simple arithmetic, you add or subtract each component of the two vectors.

For example, addition:
(0, 0, 0) + (3, 5, 7) = (3, 5, 7)

Code:
Vector3 first = Vector3(0, 0, 0);
Vector3 second = Vector3(3, 5, 7);

Vector3 result = Vector3(first.x + second.x,
                         first.y + second.y,
                         first.z + second.z);

// result.x is 3, result.y is 5, result.z is 7 

If you're using a pre-defined vector class, it will probably have an addition and subtraction operator. Here's what vector addition will generally look like:
Vector3 result = first + second;

subtraction:
(0, 0, 0) - (3, 5, 7) = (-3, -5, -7)

Code:
Vector3 first = Vector3(0, 0, 0);
Vector3 second = Vector3(3, 5, 7);

Vector3 result = Vector3(first.x - second.x,
                         first.y - second.y,
                         first.z - second.z);

// result.x is -3, result.y is -5, result.z is -7

Common uses of vector addition and subtraction

  • Applying force to an object.

If you wanted to apply gravity to an object, for example, you would add gravity to an object's velocity each frame. You would want to take the elapsed frame's time into account as well.

void ProcessGravity( float elapsedTime )
{
    Vector3 myVelocity = (5, 0, 5);
    Vector3 gravity = (0, -9.8f, 0);

    gravity *= elapsedTime;

    myVelocity = myVelocity + gravity;
}




In the above method I've defined the variables for velocity and gravity, but generally this method would be part of the object, so velocity would be a member variable. Also, gravity would usually be passed into the method, not defined within it. Finally, the vector class will likely have a += operator. So the function would be look closer to this:
void MyClass::ApplyGravity( const Vector3& gravity, float elapsedTime )
{
    m_Velocity += (gravity * elapsedTime);
}

You may notice that gravity is being multiplied by a float. That operation is generally an overloaded operator that works like such:
gravity.x *= elapsedTime;
gravity.y *= elapsedTime;
gravity.z *= elapsedTime;

No comments:

Post a Comment