OpenGL编程指南11:组合运动示例2—创建机器人手臂模型

1.源代码:


#include 
 
static int shoulder = 0, elbow = 0;
void init(void)
{
	glClearColor(0.0,0.0,1.0,0.0);
	glShadeModel(GL_FLAT);
}
void display(void)
{
	glClear(GL_COLOR_BUFFER_BIT);
	glColor3f(1.0,1.0,1.0);

	//采用移动局部坐标的方式
	glPushMatrix(); //压入栈顶
	glTranslatef(-1.0, 0.0, 0.0);   //局部坐标在矩形中心,移到边上
	glRotatef((GLfloat)shoulder, 0.0,0.0,1.0);
	glTranslatef(1.0,0.0,0.0);

	glPushMatrix(); //在压入栈顶
	glScalef(2.0,0.4,1.0);
	glutWireCube(1.0);
	glPopMatrix(); //此时局部坐标中心仍然在长方体中间

	glTranslatef(1.0,0.0,0.0);  //局部坐标中心移到关节处
	glRotatef((GLfloat)elbow, 0.0,0.0,1.0);
	glTranslatef(1.0,0.0,0.0);  //平移到第二个立体中心

	glPushMatrix();  //在压入栈顶
	glScaled(2.0,0.4,1.0);
	glutWireCube(1.0);
	glPopMatrix();

	glPopMatrix();
	glutSwapBuffers();
}
void reshape(int w,int h)
{
	glViewport(0,0,(GLsizei)w,(GLsizei)h);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(65,(GLdouble)w/(GLdouble)h,1.0,20.0);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	gluLookAt(0.0,0.0,6.0,
			  0.0,0.0,0.0,
			  0.0,1.0,0.0 );
}

void keyboard(unsigned char key, int x, int y)
{
	switch(key)
	{
	case 's':  //rotates at shouder
		shoulder = (shoulder + 5)%360;
		glutPostRedisplay();
		break;
	case 'S':
		shoulder = (shoulder + 5)%360;
		glutPostRedisplay();
		break;
	case 'e':
		elbow = (elbow + 5)%360;
		glutPostRedisplay();
		break;
	case 'E':
		elbow = (elbow + 5)%360;
		glutPostRedisplay();
		break;
	default:
		break;
	}
}
int main(int argc, char** argv)
{
	glutInit(&argc,argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
	glutInitWindowPosition(200,200);
	glutInitWindowSize(400,400);
	glutCreateWindow(argv[0]);
	init();
	glutDisplayFunc(display);
	glutReshapeFunc(reshape);
	glutKeyboardFunc(keyboard);
	glutMainLoop();
	return 0;
}

2.输出结果

OpenGL编程指南11:组合运动示例2—创建机器人手臂模型_第1张图片

你可能感兴趣的:(计算机图像学,OpenGL编程)