#include <GL/glut.h>
#include <stdio.h>
float x1=-0.4, y1=0, x2=0, y2=0, angle=0;
void display()
{
glEnable(GL_DEPTH_TEST);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glTranslatef(x1, y1, 0);//要掛在哪裡?
glRotatef(angle, 0,0,1);
glTranslatef(-0.25, -0.11, 0);
glColor3f(1,1,0);
glutSolidTeapot(0.2);
glPopMatrix();
glPushMatrix();
glTranslatef(x2, y2, 0);
glColor3f(1,0,0);
glutSolidTeapot(0.2);
glPopMatrix();
glFlush();///先不用 glutSwapBuffers(); 配合 glutInitDisplayMode(GLUT_DOUBLE);
}
void keyboard(unsigned char key, int x, int y)
{
if(key=='1') x1+=0.1;
if(key=='2') x1-=0.1;
if(key=='3') y1+=0.1;
if(key=='4') y1-=0.1;
if(key=='5') angle+=10;
if(key=='6') angle-=10;
printf("%f %f\n", x1, y1);
glutPostRedisplay();
}
int main(int argc, char**argv)
{
glutInit(&argc, argv);
glutCreateWindow("Robot3D");
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
glutMainLoop();
}
手臂茶壺,可以使用1,2,3,4,5,6來控制茶壺手臂。
#include <GL/glut.h>
float oldX=0,oldY=0;
float angle[10]={0,0,0,0,0,0,0,0,0,0};
int now;
void motion(int x,int y)
{
angle[now]-=y-oldY;
oldY=y;
oldX=x;
}
void keyboard(unsigned char key,int x,int y)
{
if(key=='1') now=1;
if(key=='2') now=2;
if(key=='3') now=3;
if(key=='4') now=4;
glutPostRedisplay();
}
void drawBody(){
glPushMatrix();
glScalef(1.1, 0.55, 0.55);
glutSolidCube(1);
glPopMatrix();
}
void drawArm(){
glPushMatrix();
glScalef(0.66, 0.33, 0.33);
glutSolidCube(1);
glPopMatrix();
}
void display()
{
{ ///Lighting
glColor3ub(100,130,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);
glRotatef(angle[1], 0,0,1);
glTranslatef(0.25, 0,0);
drawArm();
glPushMatrix();
glTranslatef(0.25, 0, 0);
glRotatef(angle[2], 0,0,1);
glTranslatef(0.25, 0,0);
drawArm();
glPopMatrix();
glPopMatrix();
glPushMatrix();
glTranslatef(-0.5, 0, 0);
glRotatef(-angle[3], 0,0,1);
glTranslatef(-0.25, 0,0);
drawArm();
glPushMatrix();
glTranslatef(-0.25, 0, 0);
glRotatef(-angle[4], 0,0,1);
glTranslatef(-0.25, 0,0);
drawArm();
glPopMatrix();
glPopMatrix();
drawBody();
glFlush();
}
void mouse(int button, int state, int x, int y){
if(state==GLUT_DOWN) { oldX=x; oldY=y; }
}
void timer(int t)
{
glutTimerFunc(20, timer, t+1);
//angle++;
glutPostRedisplay();
}
int main(int argc, char**argv)
{
glutInit(&argc, argv);
glutCreateWindow("WTF");
glutDisplayFunc(display);
glutTimerFunc(20, timer, 0);
glutMouseFunc(mouse);
glutMotionFunc(motion);
glutKeyboardFunc(keyboard);
glutMainLoop();
}
沒有留言:
張貼留言