2018年3月19日 星期一

Week 04 光

右手定則

glRotatef( 角度, X軸, Y軸, Z軸);
X軸:正值:右手大拇指向右,轉動向內 負值:右手大拇指向左,轉動向外
Y軸:正值:右手大拇指向上,轉動向內 負值:右手大拇指向下,轉動向外
Z軸:正值:右手大拇指向內,逆時針轉動 負值:右手大拇指向外,順時針轉動

期中考考題

glPushMatrix(); ///備份矩陣
glTranslaref( x, y, z); ///移動
glRotatef(angle,x,y,z); ///角度
glScalef(x,y,z); ///放大縮小
glBegin(GL_POLYGON); ///開始畫
glColor3f(x,y,z); ///顏色
glVertex3f(x,y,z); ///頂點
glEnd(); ///結束畫 Begin()對應
glPopMatrix(); ///還原矩陣
#include <GL/glut.h>
#include <stdio.h>
float angle=0, teapotX=0, teapotY=0;///加上移動的座標
int oldX=0, oldY=0, nowRotate=0;///0:translate, 1:rotate
void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);///2種模式
    glPushMatrix();///備份矩陣
        glTranslatef(teapotX, teapotY, 0);///轉完的茶壺再移動
        glRotatef(angle,0,0,1);///旋轉angle度
        glutSolidTeapot(0.3);
    glPopMatrix();///還原矩陣
    glutSwapBuffers();
    ///printf("%.1f\n", angle);angle++;///每次角度加1度
}
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(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;///做完計算,把oldX oldY記起來
    glutPostRedisplay();///重畫畫面Redisplay
}
int main(int argc, char*argv[])///進階的main()參數(個數,字串)
{
    glutInit(&argc, argv);///進階參數,初始GLUT
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);///2種模式
    glutCreateWindow("Week04 transformation");

    ///glutIdleFunc(display);///很閒 Idle,去重畫
    glutDisplayFunc(display);
    glutMouseFunc(mouse);///滑鼠按鈕
    glutMotionFunc(motion);///滑鼠移動
    glutMainLoop();///主要迴圈
}

沒有留言:

張貼留言