2024年3月11日 星期一

電腦圖學坐牢中 week04

1. week04_mouse_glScalef

1-1. 安裝 freeglut,將 lib 的 libfreeglut.a 複製後改成 libglut32.a

1-2. File ⮕ New ⮕ Project,開啟 GLUT project,檔案名稱 week04_mouse_glScalef

1-3. 將十行程式碼貼上

1-4. 新增程式清空背景的顏色

```cpp

void display(){

    glClearColor(1, 1, 0.9, 1); ///R, G, B, A

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glColor3f(0, 1, 0);

}

```

1-5. 利用滑鼠左右移動,將茶壺放大縮小

```cpp

glPushMatrix();

    glScalef(s, s, s); ///縮放s倍

     glutSolidTeapot( 0.3 );

glPopMatrix();

void motion(int x, int y)

{

    s = 1 + (x-150) / 150.0; ///會變大變小的變數0~1~2

    display(); ///重畫畫面

}

```

2. 將公轉與自轉運用到茶壺上

2-1. File ⮕ New ⮕ Project,開啟 GLUT project,檔案名稱 week04_mouse_translate_rotate_scale(公轉)

2-2. 複製前一個程式碼

2-3. 修改、新增程式碼

```
void display()
{
    glTranslatef(teapotX, teapotY, 0);
    glRotatef(angle++, 0, 0, 1);
}

float teapotX = 0.5, teapotY = 0;

float angle = 0; ///旋轉角度

float s = 0.3;

```

2-4. File ⮕ New ⮕ Project,開啟 GLUT project,檔案名稱 week04_mouse_rotate_translate_scale(自轉)

2-5. 複製剛剛的程式碼

2-6. 交換2行程式碼,先旋轉再移動

```cpp

void display()

{

    glRotatef(angle++, 0, 0, 1); ///旋轉

    glTranslatef(teapotX, teapotY, 0);  ///移動

}

```

3. 集大成

3-1. File ⮕ New ⮕ Project,開啟 GLUT project,檔案名稱week04_keyboard_mouse_motion

3-2. 貼上10行程式碼

3-3. 寫清空背景及畫茶杯的程式碼

3-4. 加入鍵盤事件函式

```cpp

void keyboard(unsigned char key, int x, int y)

{

    printf("key: %c x: %d y: %d\n", key, x, y);

}

int main(int argc, char * argv[])

{

    glutKeyboardFunc(keyboard); ///鍵盤事件的函式

}

```

3-5. 加入滑鼠事件函式

```cpp
void mouse(int button, int state, int x, int y)

{

    teapotX[N] = (x - 150) / 150.0;

    teapotY[N] = - (y - 150) / 150.0;

    N++;

}

int main(int argc, char * argv[])

{

    glutMouseFunc(mouse); ///滑鼠事件的函式

}

```

沒有留言:

張貼留言