這是一個很簡單的OpenGL小程序,實現了點擊屏幕中矩形拖動的功能,但是我覺得對於OpenGL圖形重繪和屏幕拾取是個很好的基礎學習。自己邊學邊做了一中午寫出來的(環境是codeblocks),還希望高手能給一些指導,謝謝。
1 #include <windows.h>
2 #include <GL/glut.h>
3
4 static GLint point[2] = {400, 300}; // 矩形中心位置點坐標
5 static bool changeState = FALSE; // 點擊時鼠標位置是否在矩形中
6
7 // 繪制函數
8 void display()
9 {
10 glClear(GL_COLOR_BUFFER_BIT);
11 glColor3f(1.0, 0.0, 1.0);
12
13 glBegin(GL_POLYGON);
14 glVertex2i(point[0]-25, point[1]-25);
15 glVertex2i(point[0]+25, point[1]-25);
16 glVertex2i(point[0]+25, point[1]+25);
17 glVertex2i(point[0]-25, point[1]+25);
18 glEnd();
19
20 glFlush();
21 }
22
23 // 初始化函數
24 void init()
25 {
26 glClearColor(0.0, 0.0, 0.0, 0.0);
27
28 glMatrixMode(GL_PROJECTION);
29 glLoadIdentity();
30 glOrtho(0, 800, 600, 0, -1.0, 1.0);
31 }
32
33 // 鍵盤響應函數
34 void keyboard(unsigned char key, int x, int y)
35 {
36 switch (key) {
37 case 27:
38 exit(0);
39 break;
40
41 default:
42 break;
43 }
44 }
45
46 // 鼠標點擊響應函數
47 void mouse(int button, int state, int x, int y)
48 {
49 if( (button==GLUT_LEFT_BUTTON) && (state==GLUT_DOWN) ) {
50 // 判斷鼠標位置是否在矩形中
51 if( abs(x-point[0])<25 && abs(y-point[1])<25 ) {
52 changeState = TRUE;
53 }
54 }
55 else if( (button==GLUT_LEFT_BUTTON) && (state==GLUT_UP) ) {
56 changeState = FALSE;
57 }
58 }
59
60 // 鼠標移動響應函數
61 void mouseMove(int x, int y)
62 {
63 glClear(GL_COLOR_BUFFER_BIT);
64
65 if(changeState == TRUE) {
66 point[0] = x;
67 point[1] = y;
68
69 glutPostRedisplay(); // 重繪函數
70 }
71 }
72
73 int main(int argc, char** argv)
74 {
75 glutInit(&argc, argv);
76 glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
77 glutInitWindowSize(800, 600);
78 glutInitWindowPosition(100, 100);
79 glutCreateWindow("Redisplay");
80 init();
81 glutDisplayFunc(display);
82 glutMouseFunc(mouse);
83 glutMotionFunc(mouseMove);
84 glutKeyboardFunc(keyboard);
85 glutMainLoop();
86
87 return 0;
88 }