c++ - I am writing a program in OpenGL to create an oscillating pendulum -
i have figured out rotation cannot limit rotation particular angle. i'm using idlefunc increment angle theta in background. please suggest alternative or solution limit rotation angle to, say, +90 , -90 degrees. here's code:
#include<stdio.h> #include<gl/freeglut.h> #include<math.h> int n=10; glfloat v[4][3]={{0.0,0.0,1.0},{0.0,0.942809,-0.33333},{-0.816497,-0.471405,-0.33333},{0.816497,-0.471405,-0.333333}}; glfloat a[2][3]={{0.0,0.0,-0.333333},{0.0,3.0,-0.333333}}; void normalize(glfloat *p) { double d=0.0; int i; for(i=0;i<3;i++) d+=p[i]*p[i]; d=sqrt(d); if(d>0.0) for(i=0;i<3;i++) p[i]/=d; } void triangle(glfloat *a,glfloat *b,glfloat *c) { glbegin(gl_polygon); glnormal3fv(a); glvertex3fv(a); glvertex3fv(b); glvertex3fv(c); glend(); } void divide_triangle(glfloat *a,glfloat *b,glfloat *c,int n) { glfloat v1[3],v2[3],v3[3]; int j; if(n>0) { for(j=0;j<3;j++) v1[j]=a[j]+b[j]; normalize(v1); for(j=0;j<3;j++) v2[j]=a[j]+c[j]; normalize(v2); for(j=0;j<3;j++) v3[j]=c[j]+b[j]; normalize(v3); divide_triangle(a,v2,v1,n-1); divide_triangle(c,v3,v2,n-1); divide_triangle(b,v1,v3,n-1); divide_triangle(v1,v2,v3,n-1); } else triangle(a,b,c); } void tetrahedron(int n) { divide_triangle(v[0],v[1],v[2],n); divide_triangle(v[3],v[2],v[1],n); divide_triangle(v[0],v[3],v[1],n); divide_triangle(v[0],v[2],v[3],n); } glfloat theta=0.0; void display(void) { glclear(gl_color_buffer_bit|gl_depth_buffer_bit); glclearcolor(1.0,1.0,1.0,1.0); glbegin(gl_lines); glvertex3fv(a[0]); glvertex3fv(a[1]); glend(); glcolor3f(1.0,0.0,0.0); tetrahedron(n); glcolor3f(0.0,0.0,1.0); glmatrixmode(gl_modelview); glloadidentity(); gltranslatef(0.0,+3.0,-0.333333); glrotatef(theta,0.0,0.0,1.0); gltranslatef(0.0,-3.0,+0.333333); glflush(); } void myreshape(int w,int h) { glviewport(0,0,w,h); glmatrixmode(gl_projection); glloadidentity(); if(w<=h) glortho(-4.0,4.0,-4.0*(glfloat)h/(glfloat)w,4.0*(glfloat)h/(glfloat)w,-20.0,20.0); else glortho(-4.0*(glfloat)w/(glfloat)h,4.0*(glfloat)w/(glfloat)h,-4.0,4.0,-20.0,20.0); glmatrixmode(gl_modelview); } void oscillate() { theta+=2.0; glutpostredisplay() } void main(int argc,char** argv) { glutinit(&argc,argv); glutinitdisplaymode(glut_rgb|glut_depth); glutinitwindowsize(1366,768); glutcreatewindow("pendulum"); glutreshapefunc(myreshape); glutdisplayfunc(display); glutidlefunc(oscillate); glenable(gl_depth_test); glutmainloop(); }
quick 'n dirty:
void oscillate() { static float direction = 1.0f; if( theta > 90.0f ) direction = -1.0f; if( theta < -90.0f ) direction = 1.0f; theta += 2.0 * direction; glutpostredisplay() }
Comments
Post a Comment