# How to implement object velocity as a vector

I'm working on a Breakout game, and want to change the ball's movement code from how I currently do it, to something based on vectors (as I feel learning and implementing movement based on vectors will help me in the long run).

Currently I am doing something like this (Pseudocode):

``````if(ball.Y < HEIGHT)
ball.Y += 1; // I actually save a direction as well,
//and multiply this by the direction (1 or -1)
else
ball.Y -= 1;

if(ball.X < WIDTH)
ball.X += 1;
else
ball.X -=1;
``````

Anyway, you get the gist of it. My current code is actually much more verbose, but handles collisions well. Basically I am just using screen coordinates, and I find that this is probably not the best way to be doing this.

How would you implement a more correct, extensible (to other projects), way to move objects?

EDIT: I am not looking to use a 2D Vector library; more-so I am looking for an explanation of how vectors are used for movement in games, and how I can implement them myself.

-
tried to answer your question with simple terms. – Dvole Aug 1 '12 at 17:06

I'd use verlet integration:

``````class Vector {
Vector(Vector vec);//Copy constructor
Vector(float x, float y);
float x;
float y;
/* and some addition and subtraction methods */
};
class Verlet {
Verlet(float x, float y, float deltax, float deltay){
current = new Vector(x, y);
previous = new Vector(x - deltax, y - deltay)
}
Vector current;
Vector previous;
void step(){
Vector delta = current - previous;
previous = new Vector(current);
current = current + delta;
}

};
``````

This makes really easy to implement collisions and all that. Also adding gravity or dampening is simple as pie.

-

In short (and as has been mentioned by others), 2D Vectors are functionally just wrappers around a pair of values representing position, motion, or whatever in 2D space.

It sounds like you're just looking for resources to better understand them. It's hard to know what your expertise level is, so here's a link dump based on things that, from a quick glance or my past experience, I'm guessing may be useful for you:

Hope these help.

-
+1 This is an excellent answer, all these links are great! – Bloodyaugust Aug 2 '12 at 15:37

To explicitly answer your question: vectors can be used to translate objects the same way as you're currently doing it. They just wrap things up nicely, and let you write less code.

For instance, what you're likely asking for is a way to dynamically move an object based on a facing vector, as opposed to a rotation.

Lets assume we have the following class:

``````function vec2(x, y)
{
this.x = x;
this.y = y;
}

vec2.prototype.translate = function (translateBy)
{
this.x += translateBy.x;
this.y += translateBy.y;
}

vec2.prototype.multiplyByScalar = function (scalar)
{
this.x *= scalar;
this.y *= scalar;
}
``````

We can move an object with position vector `v1` along a facing vector `v2` by `moveSpeed` like so:

``````v1.translate(v2.multiplyByScalar(moveSpeed));
``````

If `v1` is `vec2(1, 1)`, `v2` is `vec2(1, 0)`, and `moveSpeed` is `2`, then after that line of code `v1` will be `vec2(3, 1)`. You'll notice that the facing vector is a unit vector: the sum of its components add to one. This means that you'll be able to use it, and your object will only ever translate `moveSpeed` units in total.

There are plenty of other cool things you can do with vectors, especially once you have collision code that returns you the vector where the collision happened. In breakout, this would allow you to set a facing vector equal to the normal of the collision vector, providing an easy way to bounce off of any surface, regardless of its rotation.

I'd recommend that you read a book or extensive article on vectors. Also, this code is JavaScript, as my Java is unreliable and rusty.

-

I'm going with pseudocode but I hope you will understand me.

First there is position:

``````struct position { x = 0; y = 0};
``````

So every object in our world has such struct. There is also another struct:

``````struct velocity {x = 100; y = 50};
``````

This means that our object is moving 100 pixels to the right and 50 pixels up each second (or any arbitary amount of time); That is a diagonal movement. If we want to reverse the ball (for example it goes to right, and we want it to go left, we just reverse the sign of x variable)

In our update function we change the position based on velocity * time;

For that we need the time passed since last time we called our function (delta) to ensure that we keep updating the loop independently of frames per second.

``````- (void) update(deltaTime)
{
struct tempPosition = ball.position;

// we get our ball position into temporary struct

tempPosition.x += velocity.x * deltaTime
//delta time is usually fraction of second,
//so our ball will move the same amount of pixels per second, no matter how often or not
//often we call our update function. So in case that half a second passed our ball
//will move for 50 pixels, and in case 0.1 seconds passed it will move only 10 pixels.

tempPosition.y += velocity.y *deltaTime;

ball.position = tempPosition;
// If your language permits for structs multiplication or assigning
// structs directly, you can shorten the method to something like

// ball.position += velocity * deltaTime;

}
``````

You should run this update method for every object on screen, for example by looping an array of all objects. Just add every object when you create it to that array and then do a for loop. Or if you are on pure C, make separate functions to update ball and paddle and run them in your main loop.

I hope that helped, if you have more questions just ask.

By the way, for collision detection it works same way, you just reverse the sign of variable in struct like this:

``````ball.velocity.x = - ball.velocity.x;
``````
-

I strongly recommend that you read a book about the topic. I recommend "3D Math Primer for Graphics and Game Development, Second Edition." by Fletcher Dunn and Ian Parberry. You can also checkout the book's webpage http://gamemath.com/ which includes powerpoint presentations of all the chapters (under Download).

-
I'm actually going to be sticking to 2d, but I'm sure the book would still be useful. – Brendan Aug 1 '12 at 18:51

I've done something similar by using 2 standard 2D vector classes (by standard 2D vector classes, I mean classes which represent an x and a y coordinate). The first vector, v1, represented the position of the ball at that moment in time, while the second, v2, represented the velocity vector. That vector represented the distance and direction traveled between two timesteps in the game, giving the following calculation for a new position (ignoring collisions, etc):

`v1 = v1 + v2;`
`//do stuff here`
`//assign new v2 here`

Hope this helps!

-
Well, I was looking to implement my own vector class; as I think it's a good way to understand the topic. – Brendan Aug 1 '12 at 15:54
A 2d vector class is very simple, it's an X and Y value, and usually has functions for addition, multiplication, subtration, division, normalization and distance. – CiscoIPPhone Aug 1 '12 at 16:23
Ok, well where is the best way to learn how to implement those methods into a custom claas....as in, a good resource for learning the math behind vectors. I've forgotten every thing I learned in physics...dumb haha – Brendan Aug 1 '12 at 18:54