This is the code for a physics project I’m wrking on right now where there are ten balls that bounce differently. But there are 2 problems:
- The balls’ y goes up in the hundred thousands, and
- The screen seemingly only refreshes when I minimize, restore, or reshape the window.
#define WIN32_LEAN_AND_MEAN
#define GLUT_DISABLE_ATEXIT_HACK
#define pio180 3.14159/180.0
#include <gl/glu.h>
#include <windows.h>
#include <gl/gl.h>
#include <gl/glut.h>
#include
#include
#include
#include
#include
#include <stdio.h>
#include <conio.h>
#include
#include <math.h>using namespace std;
struct bounce{
float speed;
float x;
float y;
float mu;
};bounce ball[11];
void reshape( int width, int height ){
GLfloat w = { -10.0, 10.0, -10.0, 10.0 };
GLfloat aspect;glMatrixMode( GL_PROJECTION );
glLoadIdentity();aspect = (GLfloat) width / (GLfloat) height;
if ( aspect <= 1.0 ){
glOrtho( w[0], w[1], w[2] / aspect, w[3] / aspect, -1.0, 1.0 );
}
else{
glOrtho( w[0] * aspect, w[1] * aspect, w[2], w[3], -1.0, 1.0 );
}glMatrixMode( GL_MODELVIEW );
glLoadIdentity();glViewport( 0, 0, width, height );
}void display(){
int i;
float pos;
for(i = 0; i < 10; i++){
glColor3f(0, 0, .1);
glPushMatrix();
glTranslatef(ball[i].x, ball[i].y, 0);
glutSolidSphere(1, 6, 6);
glPopMatrix();
}
glEnable(GL_LINES);
glVertex2f(-9, -9.5);
glVertex2f(9, -9.5);
glDisable(GL_LINES);
glutSwapBuffers();
}void showwhy(){
cout<<ball[0].y<<endl;
}void idle(){
showwhy();int i;
for(i = 0; i < 10; i++){
ball[i].y += ball[i].speed;
ball[i].speed -= 1;
if(ball[i].y < -9){
ball[i].speed = -ball[i].speed;
ball[i].speed -= ball[i].mu;
}
}
}
int main(int argc, char argv){
int i;
float temp = -9;
for(i = 0; i < 10; i++){
ball[i].mu = temp;
ball[i].y = 9;
ball[i].speed = 0;
ball[i].x = temp;
temp += 2;
}void glutInit(int *argcp, char **argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE| GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutInitWindowPosition(0, 0);
glutCreateWindow(“BOUNCY BALL by Andrew MacRobert”);
glutReshapeFunc(reshape);
glutDisplayFunc(display);
glutIdleFunc(idle);
glutMainLoop();
}