기본 화면

키보드 콜백을 이용해보았다. 방향키로 회색 사각형 오브젝트를 이동시키고, ESC키를 누르면 프로그램을 종료할 수 있도록 구현했다.

 

#include  <iostream>
#include <gl/glut.h>

double trans_left = 0, trans_up = 0;      //오브젝트 이동을 위한 변수 (좌우/위아래)

 

//디스플레이 콜백함수 
void MyDisplay() {
glClear(GL_COLOR_BUFFER_BIT); 
glColor3f(0.5, 0.5, 0.5);
glBegin(GL_POLYGON); 
glVertex3f(-0.5 + trans_left, -0.5 + trans_up, 0.0);
glVertex3f(0.5 + trans_left, -0.5 + trans_up, 0.0);
glVertex3f(0.5 + trans_left, 0.5 + trans_up, 0.0);
glVertex3f(-0.5 + trans_left, 0.5 + trans_up, 0.0);
glEnd();
glFlush();
}

void MyReshape (int NewWidth, int NewHeight) {
glViewport(0, 0, NewWidth, NewHeight);
GLfloat WidthFactor = (GLfloat)NewWidth / (GLfloat)300;
GLfloat HeightFactor = (GLfloat)NewHeight / (GLfloat)300;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1.0 * WidthFactor, 1.0 * WidthFactor,
-1.0 *HeightFactor, 1.0 * HeightFactor, -1.0, -1.0);
}

void MyKeyboard (unsigned char KeyPressed, int X,int Y) {
switch (KeyPressed) {
case 27:
exit(0);
break;
}
}

void MySpecialKey(int Key,int X, int Y)
{
switch (Key) {
case GLUT_KEY_LEFT:     //왼쪽 키
trans_left = trans_left - 0.1;
glutPostRedisplay();
break;
case GLUT_KEY_RIGHT:     //오른쪽 키
trans_left = trans_left + 0.1;
glutPostRedisplay();
break;
case GLUT_KEY_UP:      //위 키
trans_up = trans_up + 0.1;
glutPostRedisplay();
break;
case GLUT_KEY_DOWN:      //아래 키
trans_up = trans_up - 0.1;
glutPostRedisplay();
break;
}
}

int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB);
glutInitWindowSize(300, 300);
glutInitWindowPosition(0, 0);
glutCreateWindow("Keyboard Callback");
glClearColor(1.0, 1.0, 1.0, 1.0);      // 배경색 
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);


glutDisplayFunc(MyDisplay);
// ESC 키에 대한 이벤트
glutKeyboardFunc(MyKeyboard);
//방향 키에 대한 이벤트
glutSpecialFunc(MySpecialKey);
glutMainLoop();

return 0;
}

'OpenGL' 카테고리의 다른 글

[OpenGL] 5. 선형보간  (0) 2019.07.19
[OpenGL] 미니 프로젝트  (0) 2019.07.17
[OpenGL] 4. 메뉴 콜백  (0) 2019.07.16
[OpenGL] 2. 마우스 콜백  (0) 2019.07.05
[OpenGL] 1. 삼각형 그리기  (0) 2019.07.05

+ Recent posts