一.
1.將15周程式碼複製到16周新開的專案
2.
程式碼:
#include <stdio.h>///可割可棄
#include <GL/glut.h>
float angle[20]={},diff=2;
int angleID=0;
int oldX=0;
void timer(int t){
///timer裡的內容刪掉
}
void mouse(int button, int state,int x,int y){///滑鼠位置
oldX=x;
}
void motion(int x,int y){///動作控制
angle[angleID]+=x-oldX;
oldX=x;
glutPostRedisplay();
}
void keyboard(unsigned char key,int x,int y){
if(key=='4')angleID=4;
if(key=='3')angleID=3;
if(key=='2')angleID=2;
if(key=='1')angleID=1;
if(key=='0')angleID=0;
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glutSolidTeapot( 0.3 );///身體
glPushMatrix();
glTranslatef(-0.3,0,0);
glRotatef(angle[0],0,0,1);
glTranslatef(-0.3,0,0);
glutSolidTeapot( 0.3 );///左手臂(重疊了)
glPushMatrix();
glTranslatef(-0.3,0,0);
glRotatef(angle[1],0,0,1);
glTranslatef(-0.3,0,0);
glutSolidTeapot( 0.3 );///左手肘(重疊了)
glPopMatrix();
glPopMatrix();
glPushMatrix();
glTranslatef(0.3,0,0);
glRotatef(angle[2],0,0,1);
glTranslatef(0.3,0,0);
glutSolidTeapot( 0.3 );///右手臂(重疊了)
glPushMatrix();
glTranslatef(0.3,0,0);
glRotatef(angle[3],0,0,1);
glTranslatef(0.3,0,0);
glutSolidTeapot( 0.3 );///右手肘(重疊了)
glPopMatrix();
glPopMatrix();
glPopMatrix();
glutSwapBuffers();
}
int main( int argc, char ** argv )
{
glutInit( &argc, argv );
glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("week16 animation");
glutMouseFunc(mouse);
glutMotionFunc(motion);
glutKeyboardFunc(keyboard);
glutTimerFunc(0,timer,0);
glutDisplayFunc(display);
glutMainLoop();
}
結果:可以自己控制每個關節分別轉動
二.
1.寫檔案
程式碼:
for(int i=0;i<20;i++)printf("%.1f ",angle[i]);
printf("\n");
印在畫面
程式碼:
FILE*fout=NULL;///存檔
在motion函式加:
if(fout==NULL)fout=fopen("angle.txt","w+");
for(int i=0;i<20;i++)fprintf(fout,"%.1f ",angle[i]);
fprintf(fout,"\n");
程式碼:
FILE*fin=NULL;///建立空指標
void timer(int t){
glutTimerFunc(30,timer,t+1);///1秒30個影格
if(fin==NULL)fin=fopen("angle.txt","r");///開檔
for(int i=0;i<20;i++)fscanf(fin,"%f",&angle[i]);///讀數據
glutPostRedisplay();///重畫畫面
}
繪畫出你上一次寫進檔案裡的數據
p.s.更改執行目錄
並把原本在freeglut/bin裡的檔案資料跟freeglut.dll移到專案的目錄裡
三.
1.按按鍵存檔跟讀檔
程式碼:
if(key=='s'){///存檔(save)
if(fout==NULL)fout=fopen("angle.txt","w+");
for(int i=0;i<20;i++)fprintf(fout,"%.1f ",angle[i]);
fprintf(fout,"\n");
for(int i=0;i<20;i++)printf("%.1f ",angle[i]);
printf("\n");
}
if(key=='r'){///讀檔(read)
if(fin==NULL)fin=fopen("angle.txt","r");
for(int i=0;i<20;i++)fscanf(fin,"%f",&angle[i]);
glutPostRedisplay();
}
if(key=='p'){///播放(play)
}
將原本的存檔跟讀檔的程式碼移到keyboard函式裡
並將它們各自加判斷式(決定按鈕鍵)
沒有留言:
張貼留言