user717572
user717572

Reputation: 3652

How do I implement vectors (vector-math)?

Currently i'm making a breakout game, and to define objects' location or movement i'm using :

float mX, mY;
float speedX, speedY;   

And to move an object I add the speed in a certain direction to the current position (mX += speedX).

But I've read alot on that I 'should' be using vectors instead of the above, wich I now plan on doing. I've read up on some of this vector math, but I don't know how I could implement this in my game. There's alot of information on the math itself, but I couldn't find anything on the code-side of it. I could come up with:

float mX, mY;
float direction;
float velocity;  

But here i'm kinda stuck. I know I should move the object to direction with velocity, probably with a factor of time, but how ?

(btw, i''m making it with openGL-ES on Android)

Upvotes: 0

Views: 1736

Answers (1)

duffymo
duffymo

Reputation: 308988

A vector in 2D has two dimensions: (vx, vy). That's all you need.

You find the direction by calculating what's called 'unit vector': a vector of magnitude 1 that points in the direction you're going.

You calculate magnitude using this formula: magnitude = sqrt(vx*vx + vy*vy)

You get the unit vector by dividing both components by the magnitude:

(ux, uy) = (vx/magnitude, vy/magnitude)

If you are moving with a constant velocity over a time step dt, then the distance you move in each direction is:

(dx, dy) = (vx*dt, vy*dt)

This assumes no acceleration over that time period.

This is all basic vector stuff. A little reading could go a long way.

Upvotes: 3

Related Questions