2018年3月23日 星期五

Week 04 游伃瑄

(1) 在 Codeblocks 開啟 GLUT 程式

到moodle下載freeglut-MinGW-3.0.0-1.mp.zip > 解壓縮 > freeglut > lib > 
複製libfreeglut.a > 貼上並重新命名為libglut32.a > 開啟Codeblocks > File > 
New > Project > GLUT



(2) 刪除原有程式碼,並貼上上一週的滑鼠拖曳茶壺的程式碼

#include <GL/glut.h>
#include <stdio.h>
float teapotX=0,teapotY=0;
void display()
{
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
        glTranslatef(teapotX, teapotY, 0);
        glutSolidTeapot(0.3);
    glPopMatrix();
    glutSwapBuffers();
}

void motion(int x, int y)
{
    teapotX=(x-150)/150.0;
    teapotY=(150-y)/150.0;
    glutPostRedisplay();
}

int main(int argc, char **argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
    glutCreateWindow("week03 Mouse");

    glutDisplayFunc(display);
  //glutMouseFunc(mouse);
    glutMotionFunc(motion);

    glutMainLoop();
}



(3) 修改程式碼,讓茶壺可以用滑鼠來旋轉角度

#include <GL/glut.h>
#include <stdio.h>
float teapotX=0,teapotY=0,angle=0; //angle為旋轉需要的角度
void display()
{
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
        glTranslatef(teapotX, teapotY, 0);
        glRotatef(angle, 0, 0, 1); //讓茶壺對著(0,0,1)Z軸做旋轉角度
        glutSolidTeapot(0.3);
    glPopMatrix();
    glutSwapBuffers();
}

void mouse(int buttom, int state, int x, int y)
{
    printf("%d %d %d %d\n", buttom, state, x, y);
}

void motion(int x, int y)
{
    //teapotX=(x-150)/150.0;
    //teapotY=(150-y)/150.0;
    angle = x;
    glutPostRedisplay();
}

int main(int argc, char **argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
    glutCreateWindow("week03 Mouse");

    glutDisplayFunc(display);
    //glutMouseFunc(mouse);
    glutMotionFunc(motion);

    glutMainLoop();
}




(3) 但茶壺無法連續旋轉、連續移動
所以必須在做修改,讓茶壺能更順利的移動旋轉

#include <GL/glut.h>

#include <stdio.h>

float teapotX=0,teapotY=0,angle=0;
int nowRotate=0, oldx=0, oldy=0; //用來紀錄移動前的x,y座標

void display()
{
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
        glTranslatef(teapotX, teapotY, 0);
        glRotatef(angle, 0, 0, 1);
        glutSolidTeapot(0.3);
    glPopMatrix();
    glutSwapBuffers();
}

void mouse(int buttom, int state, int x, int y)
{
    if(buttom==GLUT_LEFT_BUTTON && state==GLUT_DOWN) 
         nowRotate=1; //左鍵做旋轉
    if(buttom==GLUT_RIGHT_BUTTON && state==GLUT_DOWN) 
         nowRotate=0; //右鍵移動
    
    oldx=x; oldy=y;
}

void motion(int x, int y)
{
    if(nowRotate==1){
        angle+=(x-oldx);
    }
    else{
        teapotX+=(x-oldx)/150.0;
        teapotY+=(oldy-y)/150.0;
    }
    oldx=x; oldy=y;
    glutPostRedisplay();
}

int main(int argc, char **argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
    glutCreateWindow("week04 Mouse");

    glutDisplayFunc(display);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);

    glutMainLoop();
}








沒有留言:

張貼留言