Movement in game programming

I will be explaining you the basics of movement in 2D Games. Its a very simple concept which anyone can implement in their respective framework after understanding the basics.

Its done by repeatedly calculating new position from the previous coordinates. Its pure 2D vector maths, so u should be familiar with that also. So now here the is the formula known to Game programmers as

"MOVEMENT FORMULA" :

New position = Old position + Speed * Direction

This is the basic formula which makes anything move in games.

If you want to move something in X direction, simply

sprite.x = sprite.x + sprite.speed * sprite.direction;

Similarly to move in Y direction :

sprite.y = sprite.y + sprite.speed * sprite.direction

For eg:

You have to move a bird from one side of the screen to other, in X axis only. So you set the starting coordinates to lets suppose (-10,0), set up its speed ,suppose 5 and direction 1 .

Now lets apply this formula and move the bird.

bird.x = bird.x + bird.speed*bird.dir;

In the first frame:

-10 + 5*1 = 5

Next frame

-5 + 5*1 = 0

next frame

0 + 5*1 = 5;

and so on.....

So bird will first be rendered at (-10,0)

in the next frame (-5,0) then (0,0) then (5,0) and so on......this will give you an illusion of movement of the bird.

If you want to make it move in the opposite direction simply take direction as -1.

Now lets suppose you want to make it in a certain angle.

Simply move in both directions

Simultaneously change its X and Y co-ordinates.

Now lets get into VECTORS.

Like in this image you want to get to a specific point like you have to move from A --> B

Then A will have some cordinates and it will be a vector, similarly B will be another vector

So now we have co-ordinates,speed but we dont know the direction, for that

B - A = C

Normalizing that vector C will give us the direction, which we can then use in our movement fformula.

The point to remember is that if A has to move to point B, then

B - A will be done, if B has to move to A,

then A - B will be done.

To make it even more useful and realistic you can include more variables like

FRICTION

ACCELERATION

GRAVITY,etc.

Try this thing by actually coding it up and get first hand experience. An explaination including actual code will follow soon.

## No comments:

## Post a Comment