Othman Benchekroun
Othman Benchekroun

Reputation: 2018

Get the camera position in opengl

I know that in opengl that the camera doesn't move, but the model is moving around it. Well I need the position of the camera in MODELVIEW... Yes, I also know that there is many topics about it but I tried all what they are doing to get the camera coordinates but it always returns (0, 0, 0) (the real position of the camera).

This is what i'm trying :

GLfloat mdl[16];
float camera_org[3];
glMatrixMode( GL_MODELVIEW );
glPushMatrix();
glGetFloatv(GL_MODELVIEW_MATRIX, mdl);
camera_org[0] = -(mdl[0] * mdl[12] + mdl[1] * mdl[13] + mdl[2] * mdl[14]);
camera_org[1] = -(mdl[4] * mdl[12] + mdl[5] * mdl[13] + mdl[6] * mdl[14]);
camera_org[2] = -(mdl[8] * mdl[12] + mdl[9] * mdl[13] + mdl[10] * mdl[14]);

also tried this (as said in some topics) :

camera_org[0] = mdl[12];
camera_org[0] = mdl[13];
camera_org[0] = mdl[14];

both of them gives me the same result (0,0,0), can anyone please tell me what i'm doing wrong ??

Upvotes: 4

Views: 8734

Answers (1)

Othman Benchekroun
Othman Benchekroun

Reputation: 2018

I found the answer for this :

int viewport[4]; 
// get matrixs and viewport:
glGetDoublev( GL_MODELVIEW_MATRIX, matModelView ); 
glGetDoublev( GL_PROJECTION_MATRIX, matProjection ); 
glGetIntegerv( GL_VIEWPORT, viewport ); 
gluUnProject( (viewport[2]-viewport[0])/2 , (viewport[3]-viewport[1])/2, 
0.0, matModelView, matProjection, viewport,  
&camera_pos[0],&camera_pos[1],&camera_pos[2]);

this will give you the coordinates of the camera in the scene.

Upvotes: 4

Related Questions