Skip to content

Instantly share code, notes, and snippets.

@dufferzafar
Last active September 12, 2015 16:53
Show Gist options
  • Save dufferzafar/80e9e8b9bacacf4b896a to your computer and use it in GitHub Desktop.
Save dufferzafar/80e9e8b9bacacf4b896a to your computer and use it in GitHub Desktop.
Ball Collisions with OpenGL. 1 -> 2 -> 1
#define GLUT_DISABLE_ATEXIT_HACK
#include <windows.h>
#include <gl\glut.h>
#include <iostream>
float x1=-2.0, x2=2.0;
static int flag=1;
static int i=0;
void reshape(int w,int h)
{
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, w/h, 1, 200);
}
void drawBall(float r, float g, float b, float x, float radius)
{
glColor3f(r, g, b);
glPushMatrix();
glTranslatef(x, 0.0, -5.0);
glutSolidSphere(radius, 20, 20);
glPopMatrix();
}
void update()
{
if(flag)
{
x1 += 0.0007;
x2 -= 0.0007;
if(x2-x1 < 0.8)
{
flag=0;
i=(i+1)%2;
}
}
else
{
x1-=0.0007;
x2+=0.0007;
if(x1 < -2.0)
flag=1;
}
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
if (i)
{
drawBall(1.0,1.0,0.0, x1, 0.2);
drawBall(1.0,1.0,0.0, x1, 0.2);
drawBall(1.0,0.0,1.0, x2, 0.2);
drawBall(1.0,0.0,1.0, x2, 0.2);
}
else
{
drawBall(1.0,1.0,0.0, x1, 0.4);
drawBall(1.0,0.0,1.0, x2, 0.4);
}
update();
glutSwapBuffers();
}
int main(int argc,char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|GLUT_DEPTH);
glutInitWindowSize(400,400);
glutCreateWindow("Collision Window");
glEnable(GL_DEPTH_TEST);
glutDisplayFunc(display);
glutIdleFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment