2018年3月19日 星期一

Week04 呆江的筆記

期中重點:
glPushMatrix(); ///備份矩陣
    glTranslated(x,y,z); ///移動
    glRotated(angle,x,y,z); ///旋轉(包含角度)
    glScalef(x,y,z); ///放大縮小
    glBegin(GL_POLYGON); ///開始繪製(凸)多邊形
        glColor3f(r,g,b); ///顏色    glVertex3f(x,y,z); ///頂點
    glEnd(); ///結束繪圖
glPopMatrix(); ///還原矩陣

茶壺轉動(自動):
程式外宣告:
folat angle = 0;

display()內新增:
lPushMatrix();
     glRotatef(angle,0,0,1);  ///選轉angle度
     glutSolidTeapot(0.3);
glPopMatrix();

angle++;

main()內新增:
glutIdleFunc(display); ///有空就重畫

茶壺轉動(手動):
display()內新增
glPushMatrix();
     glRotatef(angle,0,0,1);  ///選轉angle度
     glutSolidTeapot(0.3);
glPopMatrix();

新增void motion()
void motion(int x,int y){
    angle = x;
    glutPostRedisplay();
}

main()內新增:
glutMotionFunc(motion);

執行結果:


茶壺旋轉、移動(手動):
程式外宣告:
float angle = 0, teapotX = 0, teapotY = 0;
int oldX = 0, oldY = 0, nowRotate = 0;

display()內新增:
glTranslatef(teapotX,teapotY,0);

新增void mouse():
void mouse(int button, int state, int x, int y){
    if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)    nowRotate = 1;
    ///如果是右鍵就旋轉
    if(button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)    nowRotate = 0;
    ///如果是左鍵就移動
    oldX = x; oldY = Y; ///按下的時候,把oldX, oldY記住
}

void motion()內修改:
void motion(int x,int y){
    if(nowRotate == 1)    angle += (x - oldX); ///去改變angle值 ///加上改變量
    else{
         teapotX += (x - oldX)/150.0;
         teapotY += (oldY - y)/150.0;
    }
    oldX = x;  oldY = y;
  glutPostRedisplay(); ///畫面重畫
}

執行結果:


完整程式碼:
#include <GL/glut.h>

float angle = 0,teapotX = 0,teapotY = 0;
int oldX = 0, oldY = 0, nowRotate = 0;

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 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();
}

void mouse(int button, int state, int x, int y){
    if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)    nowRotate = 1;
    if(button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)    nowRotate = 0;
    oldX = x; oldY = y;
}
int main(int argc,char** argv){
    glutInit(&argc,argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
    glutCreateWindow("Week04");

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

}





沒有留言:

張貼留言