I am trying to use the mouse to look left and right and the keyboard to move forward, backwards, left and right. I used glTranslate() to move with the keyboard but I am having trouble looking left and right with the mouse. Whenever I use the mouse to look left and right, the object rotates about the origin instead of my view. This is not what I want. I want my view to rotate left and right as if I am turning my head. Is there a way to temporarily move the origin to the camera position so that I can use glRotate() to achieve the head turning affect?
#include
#include GLfloat objectx = 0.0;
GLfloat objecty = 0.0;
GLfloat objectz = -5.0;
GLint rotation = 0;
GLint motionx = 250;
GLint motiony = 250;
void init(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_FLAT);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
glPushMatrix();
glRotatef((GLfloat) rotation, 0.0, 1.0, 0.0);
glTranslatef(objectx, objecty, objectz);
glutWireCube(1.0);
glPopMatrix();
glutSwapBuffers();
}
void reshape(int w, int h)
{
glViewport(0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0, (GLfloat) w/ (GLfloat) h, 1.0, 20.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0.0, 0.0, 0.0, 0.0, 0.0, -5.0, 0.0, 1.0, 0.0);
}
void keyboard(unsigned char key, int x, int y)
{
switch (key)
{
case 'i':
objectz += 0.1;
glutPostRedisplay();
break;
case 'k':
objectz -= 0.1;
glutPostRedisplay();
break;
case 'j':
objectx += 0.1;
glutPostRedisplay();
break;
case 'o':
objectx -= 0.1;
glutPostRedisplay();
break;
default:
break;
}
}
void motion(int x, int y)
{
if (motionx > x)
rotation = (rotation - 1) % 360;
if (motionx < x)
rotation = (rotation + 1) % 360;
glutPostRedisplay();
motionx = x;
motiony = y;
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow(argv[0]);
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMotionFunc(motion);
glutMainLoop();
return 0;
}