Hi all,
I am reading OpenGL SuperBible these days. There is a program about Animation with OpenGL in CHAPTER 2. Following is sorce code. For this example, I think the size of window is 800 * 600, viewport region is also 800 * 600, and clipping region could be (100*4/3)*100. In the code, windowWidth is clipping width, windowHeight is clipping height. But I am confused about when we check whether rectangle reach 4 edges, we just use windowWidth or windowHeight to check instead of the real window width and height. But from the result of running, I found when rectangle reach the real window width or height, it change direction rather than reach clipping width or height.
Could anyone tell me how it works? BTW, I am a novice about OpenGL. Plese give me some suggestions about how to learn it.
Thanks in advance!
#include <glut.h>
GLfloat x1 = 0.0f;
GLfloat y1 = 0.0f;
GLfloat rsize = 25;
GLfloat xstep = 1.0f;
GLfloat ystep = 1.0f;
GLfloat windowWidth;
GLfloat windowHeight;
void RenderScene()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0f, 0.0f, 0.0f);
glRectf(x1, y1, x1 + rsize, y1 - rsize);
glutSwapBuffers();
}
void TimerFunction(int value)
{
if (x1 > windowWidth - rsize || x1 < -windowWidth)
{
xstep = -xstep;
}
if (y1 > windowHeight || y1 < -windowHeight + rsize)
{
ystep = -ystep;
}
x1 += xstep;
y1 += ystep;
if(x1 > (windowWidth -rsize + xstep))
x1 = windowWidth - rsize - 1;
else if(x1 < -(windowWidth + xstep))
x1 = -windowWidth -1;
if(y1 > (windowHeight + ystep))
y1 = windowHeight-1;
else if(y1 < -(windowHeight - rsize + ystep))
y1 = -windowHeight + rsize - 1;
glutPostRedisplay();
glutTimerFunc(33, TimerFunction, 1);
}
void SetupRC()
{
glClearColor(0.0f, 0.0f, 1.0f, 1.0f);
}
void ChangeSize(int w, int h)
{
GLfloat aspectRatio;
if (h == 0)
{
h = 1;
}
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
aspectRatio = (GLfloat)w / (GLfloat)h;
if (w <=h)
{
windowWidth = 100;
windowHeight = 100 / aspectRatio;
glOrtho (-100.0, 100.0, -windowHeight, windowHeight, 1.0, -1.0);
}
else
{
windowWidth = 100 * aspectRatio;
windowHeight = 100;
glOrtho (-windowWidth, windowWidth, -100.0, 100.0, 1.0, -1.0);
}
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(800, 600);
glutCreateWindow("Bounce");
glutDisplayFunc(RenderScene);
glutReshapeFunc(ChangeSize);
glutTimerFunc(33, TimerFunction, 1);
SetupRC();
glutMainLoop();
return 0;
}