1. mouse滑鼠 👉 滑鼠一按,就會在小黑視窗出現座標
step1: 桌面有"葉正聖老師上課用軟體" freeglut 安裝,再把 lib 的 libfreeglut.a 複製 成 libglut32.a
step2: 在 CodeBlocks 開新專案,專案名稱為 "week03_mouse"
step3: 把 blog / github 的十行程式碼貼上
#include <GL/glut.h>///使用GLUT程式碼外掛,118行
void display()
{
glutSolidTeapot( 0.3 );///自己寫
glutSwapBuffers();///自己寫
}
int main(int argc, char *argv[])///我們的main函式,138行
{
glutInit(&argc, argv);///140行
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);///143行
glutCreateWindow("GLUT Shapes");///145行,建3D視窗
glutDisplayFunc(display);///148行,設定畫圖的函式
glutMainLoop();///174行,主要迴圈
}
step4: 再寫三個程式碼
1 👉 void mouse(int button, int state, int x, int y){
printf("Hello World\n");
}
2 👉 glutCreateWindow("week03 mouse");
3 👉 glutMouseFunc(mouse);
step5: 定義mouse的函式 button:左鍵,1:中鍵,2:右鍵
printf("%d %d %d\n", button, state, x, y);
2. Transformation
step1: 下載課本的範例 https://jsyeh.org/3dcg10/ 👉 [data][win32]
step2: 將windows.zip解壓縮,並將data.zip的data拉到windows資料夾
step3: 打開 Transformation 移動 (考試 : 一個佔十分)
3. 茶壺結合座標、滑鼠
step1: 開新專案,專案名稱為 "week03_mouse_glTranslate"
step2: 加新的程式碼,並且修改 mouse 函式的內容
👉 float teapotX = 0, teapotY = 0;///新加的城市,用來放茶壺的座標
👉 void mouse(int button, int state, int x, int y)
{ ///我們這裡要巧妙的修正
teapotX = (x-150)/150.0;
teapotY = -(y-150)/150.0;
} ///state->0:下去, 1:上來
display 裡新加 👉 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);///清背景
glPushMatrix();///備份矩陣
glTranslatef(teapotX, teapotY, 0);///把座標移動
glutSolidTeapot( 0.3 );
glPopMatrix();///還原矩陣
3. glRotatef 旋轉 👉 glRotatef(角度angle, x, y, z)
註: 安培右手定則 x 👉 大拇指向右, y 👉 大拇指向上, z 👉 大拇指向自己(衝出來(考))
step1: 調整角度 👉 第一張圖,以y軸為中心
X軸 👉 調整x座標,圖2
Y軸 👉 改變中心位置
Z軸 👉 調整z座標,圖3



step2: 開新專案,專案名稱為 "week03_mouse__glRotatef"
step3: 複製 "week03_mouse_glTranslate" 的程式碼step4: 新加程式碼
include 下方加上 👉 float angle = 0;///旋轉的角度
display 的 glPushMatrix(); 裡修改
👉 ///glTranslatef(teapotX, teapotY, 0);///把座標移動
glRotatef(angle, 0, 0, 1);///最難的z軸
void mouse() 函數下方新增 motion 函數的運算
👉 void motion(int x, int y)
{
angle = x;
display();
}
main 👉 glutMotionFunc(motion);///這一行,設定mouse的motion動作
4. 旋轉、移動的結合
step1: 開新專案,專案名稱為 "week03_mouse_translate_rotate"
step2: 複製 "week03_mouse__glRotatef" 的程式碼
step3: 新加程式碼
main 👉 glutKeyboardFunc(keyboard);///這一行,設定keyboard動作
在 motion 函數下 👉 void keyboard(unsigned char key, int x, int y)
{
if(key=='e') method=1; ///旋轉Rotate
if(key=='w') method=2; ///移動Translate
}
修改 motion 👉 void motion(int x, int y)
{
if(method==1){
angle += x-oldX;
}
else if(method==2){
teapotX += (x - oldX)/150.0;
teapotY += (y - oldY)/150.0;
}
oldX = x;
oldY = y;
display();
}
mouse上方 👉 int method = 1;///1:旋轉,2:移動
int oldX = 0, oldY = 0;
display 解開註解 👉 glTranslatef(teapotX, teapotY, 0);///把座標移動
未移動前 👇
旋轉、移動後 👇
沒有留言:
張貼留言