Reputation: 65
I am still learning opengl and I was working on a game similar to chicken invaders. What I am trying to do is to have a background similar to that of chicken invaders with some stars and galaxy. I did that using a quad with the size of the screen that I added texture to. Up until now all is good but I am now trying to translate this galaxy background downward so that the spaceship and the chicken seem as if they are moving forward through space. My idea is to used glutIdleFunc() function and on every iteration, I should sleep first for 30 milliseconds then update the galaxy background so that every row of pixels is moved downward by 1 row and the last row is copied to the first row. The problem is that this approach works fine for the about 15 seconds then the program stops completely and my computer hangs and freezes to the extent that I need to restart my pc. I think my approach requires ridiculously many operations every time glutIdleFunc() is called. I searched for people who faced similar situations online but I found no similar post.
int main(int argc, char** argr) {
glutInit(&argc, argr);
glutInitWindowSize(SCREEN_WIDTH, SCREEN_WIDTH);
// background is a global variable that contains the bitmap array
int err = load_image("Art/background.bmp", &background);
if(err)
{
fprintf(stderr, "%d\n", err);
exit(1);
}
glutCreateWindow("OpenGL - 2D Template");
glutDisplayFunc(Display);
glutMotionFunc(mo);
glutMouseFunc(mou);
glutIdleFunc(Animate);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
gluOrtho2D(0.0, 1000, 0.0, 600);
glutMainLoop();
}
void Animate(void)
{
msleep(300);
translate_image(&background, 30);
glutPostRedisplay();
}
void translate_image(image_t* img, const int c)
{
uint32_t copy[img->height][img->width];
for(int i = 0; i < img->height; i++)
{
for(int j = 0; j < img->width; j++)
{
copy[i][j] = img->data[i * img->width + j];
}
}
for(int i = 0; i < img->height; i++)
{
for(int j = 0; j < img->width; j++)
{
int index = (i + c) % img->height;
img->data[index * img->width + j] = copy[i][j];
}
}
}
void Display() {
glClear(GL_COLOR_BUFFER_BIT);
glEnable(GL_TEXTURE_2D);
texture = glInitTexture(background);
drawImage(texture, 0.0f, 0.0f, background.width, background.height);
glDisable(GL_TEXTURE_2D);
drawSpaceShip();
glFlush();
}
is There a more efficient way to do the same thing I am trying to do with freezing my computer every time I run it ?
Upvotes: 0
Views: 890
Reputation: 162164
You don't have to copy around the picture contents. It suffices to animate the texture coordinates, which you use to map the picture to the quad.
Also you must call glutInitDisplayMode
before glutCreateWindow
for it to have an effect. Also you don't want a single buffered framebuffer, but a double buffered one GLUT_DOUBLE
instead of GLUT_SINGLE
and call glutSwapBuffers
instead of glFinish
.
Upvotes: 1