#include float X = 0, Y = 25; void draw_line(float xa, float ya, float xb, float yb) { glPushAttrib(GL_ALL_ATTRIB_BITS); glColor3ub(128, 128, 128); glLineWidth(2); glEnable(GL_LINE_STIPPLE); glLineStipple(1, 0xFF00); glBegin(GL_LINES); glVertex2f(xa, ya); glVertex2f(xb, yb); glEnd(); glPopAttrib(); } void draw_square(float x, float y) { glPushAttrib(GL_ALL_ATTRIB_BITS); glColor3ub(255, 0, 0); glLineWidth(1); glRectf(x - 25, y - 25, x + 25, y + 25); glPopAttrib(); } void display() { // clear screen glClearColor(1, 1, 1, 0); glClear(GL_COLOR_BUFFER_BIT); // draw grey line, 2px width, stippled draw_line(-240, 0, 240, 0); // draw red square draw_square(X, Y); glutSwapBuffers(); } void normal_keys(unsigned char key, int x, int y) { if(key == 'a') X -= 4; if(key == 'd') X += 4; glutPostRedisplay(); } void timer(int) { glutPostRedisplay(); glutTimerFunc(1000.0 / 60.0, timer, 0); } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitWindowPosition(200, 50); glutInitWindowSize(480, 360); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutCreateWindow("OpenGL"); gluOrtho2D(-240, 240, -180, 180); glutDisplayFunc(display); glutKeyboardFunc(normal_keys); timer(0); glutMainLoop(); return 0; }