0

I'm trying to make a free roam camera in OpenGL. Currently the camera moves forward, backwards, left and right. My next aim is to allow it to move in the direction your looking at.

Heres my code so far:

float yawRad = Rotation -> y * (3.1415f/180);
float pitchRad = Rotation -> x * (3.1415f/180);

if(myInput.Keys[VK_W]) //Forward
{
    curPos->x += sin(yawRad) * myInput.Sensitivity;
    curPos->z -= cos(yawRad) * myInput.Sensitivity;
}
else if(myInput.Keys[VK_S]) //Backward
{
    curPos->x -= sin(yawRad) * myInput.Sensitivity;
    curPos->z += cos(yawRad) * myInput.Sensitivity;
}

if(myInput.Keys[VK_A]) //Left
{
    curPos->x -= cos(yawRad) * myInput.Sensitivity;
    curPos->z -= sin(yawRad) * myInput.Sensitivity;
}
else if(myInput.Keys[VK_D]) //Right
{
    curPos->x += cos(yawRad) * myInput.Sensitivity;
    curPos->z += sin(yawRad) * myInput.Sensitivity;
}

if(myInput.Keys[VK_E]) //Up
{
    curPos->y += myInput.Sensitivity;
}
else if(myInput.Keys[VK_Q]) //Down
{
    curPos->y -= myInput.Sensitivity;
}

myInput.Sensitivity is a float controlled by the mouse wheel, with values increasing/decreasing 0.0005.

Rotation is a vector class storing x,y,z values (float).

My question is, how can I modify my code to achieve free roam?

didierc
  • 14,572
  • 3
  • 32
  • 52
Split
  • 259
  • 2
  • 5
  • 11

1 Answers1

1

You can obtain the left, up and forward vectors of the camera from the first, second and third column of the modelview matrix - after it's been configured of course.

float mview[16];
float front[4], up[4], left[4];

glGetFloatv(GL_MODELVIEW_MATRIX, mview);
left[0] = mview[0]; left[1] = mview[1]; left[2] = mview[2]; left[3] = 1.0;
up[0] = mview[4]; up[1] = mview[5]; up[2] = mview[6]; up[3] = 1.0;
front[0] = mview[8]; front[1] = mview[9]; front[2] = mview[10]; front[3] = 1.0;

From then, you just need to add the appropriate vector to the position for movement.

if(myInput.Keys[VK_A]) //Left
{
    curPos->x += left[0] * myInput.Sensitivity;
    curPos->z += left[z] * myInput.Sensitivity;
}
else if(myInput.Keys[VK_D]) //Right
{
    curPos->x -= left[0] * myInput.Sensitivity;
    curPos->z -= left[2] * myInput.Sensitivity;
}
// etc.

See this page for further details. On the same site, this other page describes how to use rotation angles to obtain the model view matrix, hence the column vectors as shown above. The same technique (but with a slightly different coordinate system) is also used for example in the quake game engines serie.

Community
  • 1
  • 1
didierc
  • 14,572
  • 3
  • 32
  • 52
  • Thanks for the answer but I'm not kean on using that way, is there a way to do it through use of cos/sin/tan? – Split Apr 21 '13 at 23:56