I have had a problem that has been torturing me for a day now. I have many objects that I draw together in the screen. They have a standard z Axis length of 10 units, a variable width length and a variable height length. My goal was to make sure that before drawing the scene, the modelview matrix was translated properly to view the scene centered no matter the width and height of the viewport/window.
So basically the point was to figure out how to calculate the glTranslatef(0,0,Z) value.
The perspective projection was set up like this:
Where width and height is the width and height of the viewport and is updated with resizing, and pixel length is basically the width of the whole scene in units. Angle was always 45.0.
I blame my lack of precise understanding of the math behind the perspective projection for this, but I went through a lot of trial and error and figured out this value.
Aspect ratio above is the e->width/e->height of the viewport. The above seemed to be working for every scene and made me quite happy but still I did not understand why.
Then I noticed that it stopped working whenever the angle changed, so I realized 1.22 depends on the angle. That lead me to remember that 1.22 is the 90 deg - the arctan of 45.
So that lead to the final results of:
float val = 90.0 - (atanf(angle))*(180.0/_PI_); glTranslatef(0,0,(-e->pixelLength*val)/ascpectRatio);
And this seems to work all the time for any angle. It is quite interesting how I was lead to this result, but still I do not understand the perspective projection mathematics totally and am not actually sure why this works.
Can anyone enlighten me with the math behind the perspective projection and maybe help explain why this works? And of course if there is a better way to do it, (which I suspecte exists) can you explain it to me?
Thanks a lot for your time.