opengl 鼠标3D旋转简单实现

原文:http://blog.csdn.net/yhb5566/article/details/7714716


[java]  view plain copy
  1. #include <GL/glut.h>  
  2. #include <math.h>  
  3. #include <stdio.h>  
  4.    
  5. static float c=M_PI/180.0f; //弧度和角度转换参数  
  6. static int du=90,oldmy=-1,oldmx=-1//du是视点绕y轴的角度,opengl里默认y轴是上方向  
  7. static float r=1.5f,h=0.0f; //r是视点绕y轴的半径,h是视点高度即在y轴上的坐标  
  8.    
  9. void display(void)   
  10. {  
  11.     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);  
  12.    
  13.     //printf("At:%.2f %.2f %.2f\n",r*cos(c*du),h,r*sin(c*du)); //这就是视点的坐标  
  14.     glLoadIdentity();  
  15.     gluLookAt(r*cos(c*du), h, r*sin(c*du), 000010); //从视点看远点,y轴方向(0,1,0)是上方向  
  16.    
  17.     glColor3f(1.0f, 0.0f, 0.0f);  
  18.     glutWireTeapot(0.5f);  
  19.    
  20.     glFlush();  
  21.     glutSwapBuffers();  
  22. }  
  23. void Mouse(int button, int state, int x, int y) //处理鼠标点击  
  24. {  
  25.     if(state==GLUT_DOWN) //第一次鼠标按下时,记录鼠标在窗口中的初始坐标  
  26.         oldmx=x,oldmy=y;  
  27. }  
  28. void onMouseMove(int x,int y) //处理鼠标拖动  
  29. {  
  30.     //printf("%d\n",du);  
  31.     du+=x-oldmx; //鼠标在窗口x轴方向上的增量加到视点绕y轴的角度上,这样就左右转了  
  32.     h +=0.03f*(y-oldmy); //鼠标在窗口y轴方向上的改变加到视点的y坐标上,就上下转了  
  33.     if(h>1.0f) h=1.0f; //视点y坐标作一些限制,不会使视点太奇怪  
  34.     else if(h<-1.0f) h=-1.0f;  
  35.     oldmx=x,oldmy=y; //把此时的鼠标坐标作为旧值,为下一次计算增量做准备  
  36. }  
  37. void init()  
  38. {  
  39.     glEnable(GL_DEPTH_TEST);  
  40. }  
  41. void reshape(int w,int h)  
  42. {  
  43.     glViewport( 00, w, h );  
  44.     glMatrixMode( GL_PROJECTION );  
  45.     glLoadIdentity();  
  46.     gluPerspective(75.0f, (float)w/h, 1.0f, 1000.0f);  
  47.     glMatrixMode( GL_MODELVIEW );  
  48. }  
  49. int main(int argc, char *argv[])   
  50. {   
  51.     glutInit(&argc, argv);   
  52.     glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH );   
  53.     glutInitWindowPosition(100100);   
  54.     glutInitWindowSize(400400);   
  55.     glutCreateWindow("OpenGL");   
  56.     init();  
  57.     glutReshapeFunc( reshape );  
  58.     glutDisplayFunc(display);   
  59.     glutIdleFunc(display);  //设置不断调用显示函数  
  60.     glutMouseFunc(Mouse);  
  61.     glutMotionFunc(onMouseMove);  
  62.     glutMainLoop();   
  63.     return 0;   
  64. }   

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值