-
-
Save dufferzafar/f87714e6b9bfd20e33cd to your computer and use it in GitHub Desktop.
Control a ball on a line with Left & Right Keys using OpenGL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define GLUT_DISABLE_ATEXIT_HACK | |
#include <windows.h> | |
#include <iostream> | |
#include <gl\glut.h> | |
// Initial Position of the Ball | |
float x_position = 0.0; | |
float y_position = 0.0; | |
// Radius of ball | |
float radius = 0.2; | |
// Speed with which the ball tranlates | |
float speed = 0.05; | |
// Limits of line | |
float line_begin = -1.25 ; | |
float line_end = 1.25 ; | |
void resize_handler(int w,int h) | |
{ | |
glViewport(0,0,w,h); | |
glMatrixMode(GL_PROJECTION); | |
glLoadIdentity(); | |
gluPerspective(45, w/h, 1, 200); | |
} | |
void key_handler( int key, int x, int y ) | |
{ | |
if (key == GLUT_KEY_LEFT) | |
x_position -= ( x_position > line_begin ? speed : 0 ); | |
else if (key == GLUT_KEY_RIGHT) | |
x_position += ( x_position < line_end ? speed : 0 ); | |
} | |
void drawBall(float r, float g, float b, float xpos, float ypos, float rad) | |
{ | |
glColor3f(r, g, b); | |
glPushMatrix(); | |
glTranslatef(xpos, ypos, -5.0); | |
glutSolidSphere(rad, 100, 100); | |
glPopMatrix(); | |
} | |
void drawLine( float x1, float y1, float x2, float y2) | |
{ | |
glLineWidth(1.0); | |
glColor3f(1.0, 1.0, 1.0); | |
glBegin(GL_LINES); | |
glVertex3f(x1, y1, -5.0); | |
glVertex3f(x2, y2, -5.0); | |
glEnd(); | |
} | |
void display() | |
{ | |
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); | |
glMatrixMode( GL_MODELVIEW ); | |
glLoadIdentity(); | |
drawBall(1.0,1.0,0.0, x_position, y_position, radius); | |
drawLine(-1.25, -0.212, 1.25, -0.212); | |
glutSwapBuffers(); | |
} | |
int main(int argc,char **argv) | |
{ | |
glutInit(&argc,argv); | |
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|GLUT_DEPTH); | |
glutInitWindowSize(600, 600); | |
glutCreateWindow("Collision Window"); | |
glEnable(GL_DEPTH_TEST); | |
glutDisplayFunc(display); | |
glutIdleFunc(display); | |
// Resize Handler | |
glutReshapeFunc(resize_handler); | |
// Key Handler | |
glutSpecialFunc(key_handler); | |
glutMainLoop(); | |
return(0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment