views:

155

answers:

1

So this kind of on topic to my other OpenGL question (not my OpenGL ES question but OpenGL the desktop version). If you have someone press a key to move a square how do you make the square movement naturally and less jumpy but also at the same speed I have it now? This is my code for the glutKeyboardFunc() function:

void handleKeypress(unsigned char key, int x, int y) 
{
        if (key == 'w')
        {
            for (int i = 0; i < 12; i++)
            {
                if (i == 1 || i == 7 || i == 10 || i == 4)
                {
                    square[i] = square[i] + 1;
                }
            }
            glutPostRedisplay();
        }
        if (key == 'd')
        {
            for (int i = 0; i < 12; i++)
            {
                if (i == 0 || i % 3 == 0)
                {
                    square[i] = square[i] + 1;
                }
            }
            glutPostRedisplay();
        }
    if (key == 's')
    {
        for (int i = 0; i < 12; i++)
        {
            if (i == 1 || i == 7 || i == 10 || i == 4)
            {
                square[i] = square[i] - 1;
            }
        }
        glutPostRedisplay();
    }
        if (key == 'a')
        {
            for (int i = 0; i < 12; i++)
            {
                if (i == 0 || i % 3 == 0)
                {
                    square[i] = square[i] - 1;
                }
            }
            glutPostRedisplay();
        }
}

I'm sorry if this doesn't quite make sense I'll try to rephrase it in a better way if it doesn't make sense.

+1  A: 

If I understand correctly, the problem is that you modify object position on keyboard event, and request a display after that event handling.

For having a smooth animation, you should store the final position of the object at keyboard event handling, and then interpolate the intermediate object position during the rendering. The derivation of the interpolation function give the speed of the animation.

This works better if the event handling is performed in a separated thread, so the event handling doesn't block (at least for few synchronization operations) the rendering operations.

Luca