Hi!
I'm working on a small "engine" (more like a framework) for rapid 2d prototyping in c++ with SDL + OpenGL. Got most things working so far, but I'm getting a really weird problem when I try to animate a sprite sheet.
If I just load one animated or one static image it works fine, but when I add both an animated image and a non-animated image, I get this:
Mario-wearing-the-corpse-of-a-frog is the animated sprite and giant Link is (supposed to be) static.
In the first picture it's working, before the animated mario-as-frog has changed frame. But then you see what happens when the animation changes frame, both mario and static link get messed up.
Here's some of the code behind the scenes:
SpriteMaps (stole the term from Flashpunk!) contain a Texture, which is just a texture id and uv coordinates. If it's supposed to be animated I create a vector of several textures with the same ID but different uvs and then update which one we draw in the update method. If the SpriteMap only contains one frame (like Link does) I skip the update method.
Loading the spritemap:
(texture is just a class that stores texture id and uv coordinates. it can either be instantiated with a filename or texture_id)
SpriteMap::SpriteMap(char *filename, int width, int height, int frames) : height(height), frames(frames)
{
scale_x = 1;
scale_y = 1;
current_frame = 0;
delay = 10.0;
time_spent = 0;
/* if this isn't animated, skip all the fancyness and just do it */
if (frames == 1)
{
this->width = width;
texture = new Texture(filename, 0, 0, 1, 1);
return;
}
/* otherwise, do fance UV calculations */
float uvw = (static_cast<float>(width) / frames) / width;
this->width = width / frames;
Texture* temp = new Texture(filename, 0, 0, uvw, 1);
GLuint id = temp->get_id();
for (float uvx = 0; uvx < 1; uvx += uvw)
{
textures.push_back( new Texture(id, uvx, 0, uvw, 1) );
}
texture = textures[0];
}
And drawing it:
(t->x and t->w is used to access the UV coords of the texture)
void Graphics::draw_texture(Texture *t, float width, float height,
const Vector2& pos, float angle)
{
glLoadIdentity();
glTranslatef(pos.x, pos.y, 0);
glRotatef(-90.0, 0, 0, 1);
glRotatef(angle, 0, 0, 1);
glBindTexture(GL_TEXTURE_2D, t->get_id());
float half_width = width / 2;
float half_height = height / 2;
glBegin(GL_QUADS);
glVertex2f(-half_width, -half_height);
glTexCoord2f(t->x, 0);
glVertex2f(half_width, -half_height);
glTexCoord2f(t->x + t->w, 0);
glVertex2f(half_width, half_height);
glTexCoord2f(t->x + t->w, 1);
glVertex2f(-half_width, half_height);
glTexCoord2f(t->x, 1);
glEnd();
}
Hope that made some kind of sense.
I've been staring at this for the best part of two days now and I can't seem to get anywhere with it. Anyone seen anything like this before? I'm sort of new to OpenGL so I'm hoping it's something simple I'm forgetting.
Hope someone can help me!