Sight vector in OpenGL

2019-02-20 13:54发布

问题:

The problem I have is that I cant get "line of sight" vector in OpenGL. I've done some research and found that it should be Z vector after transformations, but it doesn't want to work. I've got this code to retrive velocity of the block( i want it to move foward from "camera"), but all the time it moves irrelevant to camera, but all the time same way compared to rendered world:

GLfloat matrix[16]; 
    glGetFloatv (GL_MODELVIEW_MATRIX, matrix);
    GLfloat d = sqrt( matrix[8]*matrix[8] + matrix[9]*matrix[9] + matrix[10]*matrix[10]);
    xmov = matrix[8]/d;
    ymov = matrix[9]/d;
    zmov = matrix[10]/d;

What I've done wrong?

回答1:

Okay, now after you clarified what you really want to do, I'm pretty sure this is the correct answer:

You are probably used to something called ModelView matrix. Didn't it seem strange for you that it's essentially combined of two parts? Well, it was for me, and after I thought about it for a while, it made sense. The final vertex position is calculated like this:

gl_Position = ProjectionMat * ModelViewMat * VertexPos;

You see, there's no difference for OpenGL whether you move "camera" from origin by [x,y,z] or move objects by [-x,-y,-z] - you'll get the same results. It is however useful to distinguish a "camera" position as something that can be different from the origin.

gl_Position = ProjectionMat * ViewMat * ModelMat * VertexPos;

I think the most natural way to do it is, as I said, split the calculations into two matrices : Model and View. Every object on the scene now has to change the Model matrix, and camera position is set by changing View matrix. Makes sense?

I'll give you an example. If your camera is in [5,0,0] (which corresponds to Translate(-5,0,0)), and your object in [-5,0,0], it will land 10 units from the camera. Now, when you move your camera further away from origin (increasing the first translation distance), distance between "camera" and the object grows.

The object translation is the Model, the camera translation is the View.

So it's not hard to come to conclusion, that if you want to ignore camera position, just strip the View part from the equation; every object will now be drawn without taking camera position into account, thus relative only to your viewport.

gl_Position = ProjectionMat * ModelMat * VertexPos;

Our hypothetical model will now land 5 units along the X axis from the viewport regardless of what you're currently "looking at", and that's, I think, pretty much what you wanted to achieve.

Anyway, you could probably use a nice tutorial about it



标签: opengl vector 3d