#include <gl/glut.h>
#include <math.h>
#define WIDTH 800
#define HEIGHT 800
static double PI = 3.141592653 ;
float angle=0.0 ;
int up = 1 ;
double k = 0.0 ;
double x=0.0, y=0.0 ;
void init()
{
glClearColor(0.0,0.0,0.0,0.0) ;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void myDisplay(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) ;
glShadeModel(GL_FLAT) ;
glEnable(GL_DEPTH_TEST) ;
glMatrixMode(GL_PROJECTION) ;
glLoadIdentity();
gluPerspective(90.0f, 1.0f, 1.0f, 2000.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, 0, 5, 0, 0, 0, 0, 1, 0) ;
//定义白色光源
GLfloat light_position[] = {0.0f, 5.0f, 0.0f, 1.0f};
GLfloat light_ambient[] = {1.0f, 1.0f, 1.0f, 1.0f};
GLfloat light_diffuse[] = {1.0f, 1.0f, 1.0f, 1.0f};
GLfloat light_specular[] = {1.0f, 1.0f, 1.0f, 1.0f};
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
//开启光照
glEnable(GL_LIGHT0) ;
glEnable(GL_LIGHTING) ;
glEnable(GL_LINE_SMOOTH) ;
//画摆线
glBegin(GL_LINES);
glVertex3f(x, y, 0.0);
glVertex3f(0.0, 4.0, 0.0);
glEnd();
//移动坐标系并画摆球
glTranslatef(x, y, 0.0) ;
glutSolidSphere(0.3, 40, 40) ;
glutSwapBuffers();
}
/* void myIdle()
{
//读取文件数据
//通过加速度算X,Y值
//给XY 赋值
//没有定义时间频率
if(up)
k += 0.5 ;
else if(!up)
k -= 0.5 ;
if( k > 15)
up = 0 ;
if( k < -15)
up = 1 ;
x = 5.0*sin( PI*k/180.0 ) ;
y = 5.0*( 1 - cos( PI*k/180.0 )) ;
myDisplay() ;
}*/
void TimerFunction(int value){
//k就是摆角 下面的IF 是 改变摆角的 你把IF 段注释 然后 在这里用 函数 得到 K 就可以了 。 下面的X Y就是 摆球的中心
if(up)
k += 0.5 ;
else if(!up)
k -= 0.5 ;
if( k > 30)
up = 0 ;
if( k < -30)
up = 1 ;
x = 5.0*sin( PI*k/180.0 ) ;
y = 5.0*( 1 - cos( PI*k/180.0 )) ;
glutPostRedisplay();
glutTimerFunc(5,TimerFunction,1);
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE|GLUT_DEPTH);
glutInitWindowPosition(100, 100);
glutInitWindowSize(WIDTH, HEIGHT);
glutCreateWindow("单摆光照演示");
init();
glutDisplayFunc(myDisplay);
//glutIdleFunc(myIdle);
glutTimerFunc(5,TimerFunction,1);
glutMainLoop();
return 0;
}