Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to do 2D animation?

Tags:

c++

graphics

I'm writing a 2D animation class, and I've got TGA pictures in which the player animation is stored. These pictures are 8x8 tiles (so on each row there are 8 frames of a moving character)

However, I don't have a clue on how to animate this in code.

I was thinking about updating it by moving the u-v coordinates each frame and returning only the current frame. How can I do this?

like image 336
MrFronk Avatar asked Dec 22 '22 06:12

MrFronk


2 Answers

Sup dawg.

Seeing as you're using the UV coordinates of the texture that contains all your animation states, you'll need to convert from pixel coordinates to UV coordinates.

If your sprite is 32 pixels wide and your texture is 256 pixels wide (thus containing 8 frames), you'll want to divide the width of the sprite by the width of the texture, giving you a number between... 0 and 1! This is your offset. To get a frame from your strip, simply do:

float step_size_x = (float)(width) / (float)(texture_width);
float step_size_y = (float)(height) / (float)(texture_height);

float begin_u = step_size_x * step_current_x;
float begin_v = step_size_y * step_current_y;
float end_u = begin_x + step_size_x; // basically, if you want sprite 0, you go from 0 to the x of sprite 1
float end_v = begin_y + step_size_y;

And that's it! Now if you want to copy the portion of the texture, that would be the following in OpenGL:

glBindTexture(GL_TEXTURE_2D, texture_id);
glBegin(GL_TRIANGLE_STRIP);
    glTexCoord2f(begin_u, begin_v);   glVertex3f(x - (width / 2), y - (height / 2), 0);
    glTexCoord2f(end_u, begin_v);     glVertex3f(x + (width / 2), y - (height / 2), 0);
    glTexCoord2f(begin_u, end_u);     glVertex3f(x - (width / 2), y + (height / 2), 0);
    glTexCoord2f(end_u, end_u);       glVertex3f(x + (width / 2), y + (height / 2), 0);
glEnd(); 

Now that I've given you a complete code sample, will you please stop bothering me about your game? :P

like image 158
knight666 Avatar answered Dec 29 '22 14:12

knight666


Your question is quite broad, so here a broad response ;)

Since Qt4.6 (one month old) there is an animation framework. It seems very interesting (no time yet to really code with it).

As it's Qt, it means nice API, multiplateform, good documentation and probably decent performances.

http://qt.nokia.com/products/appdev/add-on-products/catalog/4/Utilities/qtanimationframework

Of course, maybe you don't want to depend on Qt.

like image 31
Tristram Gräbener Avatar answered Dec 29 '22 14:12

Tristram Gräbener