Could use some help with WASD movement and mouselook in OpenGL
1 replies, posted
I'm having some trouble with the translation and rotation matrices in a little test OpenGL application I'm creating. I want to simulate WASD movement and mouselook navigation, the same way that most FPS games does.
If I run this code:
[lua] glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(90.f, ((float)800/(float)600), 1.f, 500.f);
glTranslatef(camx, -50.f, camz);
glRotatef(((float)mousex)/8, 0.f, 1.f, 0.f);[/lua]
The camera will rotate around the 0,0,0 world coordinates rather than rotating around itself.
However, the WASD movement work as intended, when you hold W you move foward in the direction the camera is pointing.
If I run this code:
[lua] glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(90.f, ((float)800/(float)600), 1.f, 500.f);
glRotatef(((float)mousex)/8, 0.f, 1.f, 0.f);
glTranslatef(camx, -50.f, camz);[/lua]
The camera will rotate around itself, like it should, but the WASD movements are relative to the world coordinates rather than the camera coordinates.
Does anyone know how to make this work as intended?
Use the second code, but the translation needs to be in the camera's "model space", so you need to rotate the translation vector.
If you look at how a matrix is stored, the first row is the local X axis, the second row is the local Y axis, the third row is the local Z axis and the final row is the translation - You want to be moving along the local Z axis. (Although that's for DirectX, I believe in OpenGL the rows and columns are swapped around.)
Here's my local translation method that I use, but as above it's written for DirectX:
[cpp]void CSceneNode::MoveLocal( const D3DXVECTOR3 &Movement )
{
// Add movement in model space into position vector
m_Translation += D3DXVECTOR3( &m_RotationMatrix._11 ) * Movement.x + D3DXVECTOR3( &m_RotationMatrix._21 ) * Movement.y + D3DXVECTOR3( &m_RotationMatrix._31 ) * Movement.z;
m_MatricesDirty = true;
}[/cpp]
Sorry, you need to Log In to post a reply to this thread.