Monday, October 2, 2017

opengl - keyboard I 讀取鍵盤(一)

---

絕對不能忘記一定要加進去的程式碼

glutIdleFunc(render); //設置全局的回調函數 

---

程式碼:


#include "GL\freeglut.h"

float triangle_r = 1;
float triangle_g = 1;
float triangle_b = 1;

void render()
{
 glClearColor(0, 0, 0, 1);  //清除畫面的顏色
 glClear(GL_COLOR_BUFFER_BIT);   //清除畫面
 glLoadIdentity(); //不讓之前殘留的矩陣資料影像後面的運算

 //開始畫圖
 glBegin(GL_TRIANGLES); //設定畫的圖為三角形
 glColor3f(triangle_r, triangle_g, triangle_b); glVertex2f(-0.5, -0.5);
 glColor3f(triangle_r, triangle_g, triangle_b); glVertex2f(0.5, -0.5);
 glColor3f(triangle_r, triangle_g, triangle_b); glVertex2f(0, 0.5);
 glEnd();
 //結束畫圖

 glutSwapBuffers(); //把畫好的東西刷上去
}

void keyboard(unsigned char key, int x, int y)
{
 if (key == 27) //按下[ESC]鍵
 {
  exit(0); //離開
 }

 if (key == 'f') //全螢幕
 {
  glutFullScreen();
  
 }

 if (key == 'r') //把顏色改成紅的
 {
  triangle_r = 1;
  triangle_g = 0;
  triangle_b = 0;

 }

 if (key == 'g') //把顏色改成綠的
 {
  triangle_r = 0;
  triangle_g = 1;
  triangle_b = 0;
 }

 if (key == 'b') //把顏色改成藍的
 {
  triangle_r = 0;
  triangle_g = 0;
  triangle_b = 1;
 }

 glutDisplayFunc(render); //呈現
}

int main(int argc, char** argv)
{

 glutInit(&argc, argv);//初始化glut

 glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE); //初始化顯示器
 glutInitWindowPosition(100, 100); //初始化視窗左上角的位置
 glutInitWindowSize(600, 600); //初始化視窗大小
 glutCreateWindow("DING"); //視窗名稱

 glutIdleFunc(render); //設置全局的回調函數 

 glutDisplayFunc(render); //顯示器
 glutKeyboardFunc(keyboard); //呈現

 glutMainLoop();
 return 0;
}


---

運行結果:


No comments:

Post a Comment