Code Block 開新專案 (Console application )
在 Project -> Build options 增加路徑
main 的glutTimerFunc( , , ); 刪掉
加入內插公式///(1-a)*Old + (a)*New
程式碼:
#include <GL/glut.h>
#include <stdio.h>///寫檔案
FILE * fout=NULL; ///file output
FILE * fin=NULL; ///file input
float oldX=0, oldY=0, x=0, y=0;
float angle[8]={0}, angleOld[8], angleNew[8];///
int now;
void readNew(){///讀檔
if(fin==NULL) fin=fopen("a.txt", "r");
for(int i=0;i<8;i++){
angleOld[i]=angleNew[i];///舊的動作被新的動作取代,然後就可以再做下一個動作
fscanf(fin, "%f", &angleNew[i]);
printf("%f ",angleNew[i]);
}
printf("\n");
}
void timerPlay(int t){
glutTimerFunc(20, timerPlay, t+1);
float a=(t%50)/50.0;
if(t%50==0) readNew();
for(int i=0;i<8;i++){
angle[i]=(1-a)*angleOld[i]+(a)*angleNew[i];///內插公式
}
glutPostRedisplay();
}
void keyboard(unsigned char key, int x, int y){
if(key=='p') glutTimerFunc(20, timerPlay, 0);
if(key=='s') {
if(fout==NULL) fout=fopen("a.txt", "w+");///寫檔
for(int i=0;i<8;i++){
fprintf(fout, "%.1f\t", angle[i]);
printf("%.1f\t", angle[i]);
}
fprintf(fout, "\n");
printf("\n");
}
if(key=='1') now=1;
if(key=='2') now=2;
if(key=='3') now=3;
if(key=='4') now=4;
if(key=='a') x-=0.1;
if(key=='d') x+=0.1;
glutPostRedisplay();
}
void motion(int x, int y){
angle[now]-= y-oldY;
if(angle[now]>60) angle[now]=60;
if(angle[now]<0) angle[now]=0;
oldY=y; oldX=x;
glutPostRedisplay();
}
void drawBody(){
glPushMatrix();
glScalef(1, 0.5, 0.5);
glutSolidCube(1);
glPopMatrix();
}
void drawArm(){
glPushMatrix();
glScalef(0.6, 0.3, 0.3);
glutSolidCube(1);
glPopMatrix();
}
void display(){
{ ///Lighting
glColor3ub(166,132,100);
GLfloat pos[]={0, 0, -1, 0};
glLightfv(GL_LIGHT0, GL_POSITION, pos);
glEnable(GL_LIGHT0);
//glEnable(GL_LIGHTING);
glEnable(GL_DEPTH_TEST);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
glPushMatrix();
glTranslatef(0.5, 0, 0);///最後一步, 把樓下的 "會對Arm Joint做旋轉的東西" 再移到右上 掛上去 ver 4
glRotatef(angle[1], 0,0,1);///把下面整團, 都對中間做旋轉 ver 3
glTranslatef(0.25, 0,0);///這是把它往右移, Arm Joint在中間 ver 2
drawArm();///這是個Arm ver 1 Right Upper Arm
glPushMatrix();
glTranslatef(0.25, 0, 0);
glRotatef(angle[2], 0,0,1);
glTranslatef(0.25, 0,0);
drawArm(); ///Right Lower Arm
glPopMatrix();
glPopMatrix();
glPushMatrix();
glTranslatef(-0.5, 0, 0);
glRotatef(-angle[3], 0,0,1);
glTranslatef(-0.25, 0,0);
drawArm();///Left Upper Arm
glPushMatrix();
glTranslatef(-0.25, 0, 0);
glRotatef(-angle[4], 0,0,1);
glTranslatef(-0.25, 0,0);
drawArm(); ///Left Lower Arm
glPopMatrix();
glPopMatrix();
drawBody();
glFlush();
}
void mouse(int button, int state, int x, int y){
if(state==GLUT_DOWN) { oldX=x; oldY=y; }
}
int main(int argc, char**argv)
{
glutInit(&argc, argv);
glutCreateWindow("T-R-T test");
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);///加上keyboard
glutMouseFunc(mouse);
glutMotionFunc(motion);
glutMainLoop();
}
沒有留言:
張貼留言