week 04 Translate,Rotate,Scale,矩陣Matrix--Push,Pop
step 1.簡單範例
static void display(void)
{
const double t = glutGet(GLUT_ELAPSED_TIME) / 1000.0; //時間函數
const double a = t*90.0; //a隨時間函數變化
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//glColor3d(1,0,0);
glPushMatrix(); //備份矩陣
glTranslated(-2.4,1.2,-6); //移動 //d是浮點數
//右手座標系統
glRotated(60,1,0,0); //沿著某軸轉動幾度 //沿著x軸轉動60度
glRotated(a,0,0,1); //a隨時間函數變化
glScaled(2, 2, 2); //縮放 //放大兩倍 //參考2
glColor3f(0,1,1); //改顏色
glutSolidTeapot(1); //茶壺
glutSolidSphere(1,slices,stacks);
glPopMatrix(); //還原矩陣
glPushMatrix();
glTranslated(0,1.2,-6);
glRotated(60,1,0,0);
glRotated(a,0,0,1);
glColor3f(1,1,0);
glutSolidTeapot(1);
glutSolidCone(1,1,slices,stacks);
glPopMatrix();
glPushMatrix();
glTranslated(2.4,1.2,-6);
glRotated(60,1,0,0);
glRotated(a,0,0,1);
glColor3f(1,0,1);
glutSolidTeapot(1);
glutSolidTorus(0.2,0.8,slices,stacks);
glPopMatrix();
...
1.

2.

step 2.實作
#include <GL/glut.h>
#include <stdio.h>
float dx=0,dy=0,dz=0;
int oldX=0,oldY=0,oldZ=0;
void display()
{
const double t = glutGet(GLUT_ELAPSED_TIME) / 1000.0;
const double a = t*90.0;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3d(1,0,0);
glPushMatrix();
glTranslated(dx,dy,dz);
//glRotated(60,1,0,0);
//glRotated(a,1,0,0);
//glScaled(3,3,3);
//glutWireSphere(1,slices,stacks);
glutSolidTeapot(0.3);
glPopMatrix();
glutSwapBuffers();
}
void motion(int x, int y)
{
dx +=(x-oldX)/150.0; //At the previous point, add the displacement.
dy += -(y-oldY)/150.0;
oldX = x;
oldY = y;
glutPostRedisplay(); // Redraw
}
void mouse(int button, int state, int x, int y)
{
if(state == GLUT_DOWN)
{
oldX = x;
oldY = y;
}
if(state == GLUT_UP)
{
printf("彈起來了\n");
}
}
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("Week04");
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutMotionFunc(motion);
glutMainLoop();
}
#include <stdio.h>
float dx=0,dy=0,dz=0;
int oldX=0,oldY=0,oldZ=0;
void display()
{
const double t = glutGet(GLUT_ELAPSED_TIME) / 1000.0;
const double a = t*90.0;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3d(1,0,0);
glPushMatrix();
glTranslated(dx,dy,dz);
//glRotated(60,1,0,0);
//glRotated(a,1,0,0);
//glScaled(3,3,3);
//glutWireSphere(1,slices,stacks);
glutSolidTeapot(0.3);
glPopMatrix();
glutSwapBuffers();
}
void motion(int x, int y)
{
dx +=(x-oldX)/150.0; //At the previous point, add the displacement.
dy += -(y-oldY)/150.0;
oldX = x;
oldY = y;
glutPostRedisplay(); // Redraw
}
void mouse(int button, int state, int x, int y)
{
if(state == GLUT_DOWN)
{
oldX = x;
oldY = y;
}
if(state == GLUT_UP)
{
printf("彈起來了\n");
}
}
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("Week04");
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutMotionFunc(motion);
glutMainLoop();
}
沒有留言:
張貼留言