User Interaction with OpenGL: Keyboard and Mouse Input Handling
This guide covers user interaction methods in OpenGL using keyboard and mouse inputs. Learn how to implement callback functions for keyboard (e.g., exiting with ESC or rotating an object with 'a' and 's') and mouse inputs (detecting clicks and actions based on button state). The keyboard function modifies a global variable 'Theta' that controls rotation, while mouse interactions can also trigger changes based on button presses. Use GLUT functions like glutKeyboardFunc and glutMouseFunc to set up your input handling effectively within the main program.
User Interaction with OpenGL: Keyboard and Mouse Input Handling
E N D
Presentation Transcript
Interaction I • Allowing the user to interact with the system. • Interaction through keyboard or mouse • For example to exit when you hit esc • The keyboard and mouse call back functions are called using: glutKeyboardFunc(keyboard); glutMouseFunc(mouse); called in the main program before the glMainloop • The keyboard and mouse functions are user defined function
Example of the keyboard function void keyboard(unsigned char key, int x, int y) {/* Details follows*/ if(key==27) exit(1); if (key == 'a') {if(++Theta > 359) Theta = 0;} else if(key == 's') {if(--Theta < 0) Theta = 359;} glutPostRedisplay(); }
Keyboard Interaction • Theta is a global integer variable defining the angle of rotation • The function changes the global variable Theta according to the key pressed and redisplay or repaint the window • If the key pressed is the ESC exit the application • If ‘a’ is pressed the rotation is clockwise (increment Theta) • If ‘s’ is pressed the rotation is counter (Decrement Theta) • glutPostRedisplay(); • call the display function again. • we can not call display directly.
Mouse Example void mouse(int button, int state, int x, int y) { if(state == GLUT_DOWN) { if(button==GLUT_LEFT_BUTTON) {if(++Theta > 359) Theta = 0;} else /* GLUT_RIGHT */ {if(--Theta< 0) Theta = 359;} } } else { /* GLUT_UP */ } glutPostRedisplay(); }
Mouse interaction • glutMouseFunc(mouse); is the call back function • If a mouse is clicked there are two possibilities: The left button or the right one • Also when it is released, there could be some action for example redrew the window.