正交投影 - 适合屏幕的物体?

时间:2014-06-03 19:43:42

标签: java opengl matrix lwjgl projection

我使用opengl(lwjgl)进行编程并构建自己的迷你库。采用投影类型的我的相机构建其投影矩阵,如下所示:

this.aspect = (float) Display.getWidth() / (float) Display.getHeight();
this.top = (float) (Math.tan(Math.toRadians(fov) / 2));
this.bottom = -top;
this.right = top * aspect;
this.left = -right;
if(type == AGLProjectionType.PERSPECTIVE){
    float aspect = 800.0f / 600.0f;
    final double f = (1.0 / Math.tan(Math.toRadians(fov / 2.0)));
    projection = new Matrix4f();
    projection.m00 = (float) (f / aspect);
    projection.m11 = (float) f;
    projection.m22 = (far + near) / (near - far);
    projection.m23 = -1;
    projection.m32 = (2 * far + near) / (near - far);
    projection.m33 = 0;
}
else if(type == AGLProjectionType.ORTHOGONAL){
    projection.m00 = 2 / (right - left);
    projection.m03 = -(right + left) / (right - left);
    projection.m11 = 2 / (top - bottom);  
    projection.m13 = -(top + bottom) / (top - bottom);
    projection.m22 = -2 / (far - near);

}

到目前为止一切顺利。 现在,VBO输入,因此对象的原始网格 - 例如四边形 - 我保持在标准化维度中,因此值范围为[-1 | 1]。 如果我想缩放它,我将模型矩阵缩放到一个值,并移动它我翻译模型矩阵。 我的问题是:这都是相对价值观。如果我说" matrix.scale(0.5f,0.5f,0.5f)"该对象将占用其先前大小的一半。但是,如果我想要一个500像素宽度的对象呢?我怎么算这个呢?或者,如果我想要对象是Screen.width / heiht,并且x = -Screen.width * 0.5和y = -Screen.height * 0.5 - 那么一个对象将填满屏幕并且其位置在左上角屏幕?我必须借助投影矩阵计算一些东西 - 对吧?但是如何?

1 个答案:

答案 0 :(得分:1)

不完全是你问的问题,但也许有帮助。使用此代码设置摄像机,使屏幕坐标与世界坐标匹配,视口的左下角对于X和Y为零。正交投影。

        case TwoD:
        {
            projectionMatrix.resetToZero();

            projectionMatrix._11 = 2.0f/(float)this.viewPort.Width;
            projectionMatrix._22 = 2.0f/(float)this.viewPort.Height;
            projectionMatrix._33 = -2.0f/(this.farClip-this.nearClip);
            projectionMatrix._43 =  -1* this.nearClip;

            projectionMatrix._44 = 1.0f;

            float tx = -0.5f* (float)this.viewPort.Width;
            float ty = -0.5f* (float)this.viewPort.Height;  
            float tz = this.nearClip +0.1f;     //why +0.1f >> so that an object with Z = 0 is still displayed

            viewMatrix.setIdetity();
            viewMatrix._22 = 1.0f;
            viewMatrix._41 = tx;
            viewMatrix._42 = ty;
            viewMatrix._43 = -tz;
            break;
        }

至于您的问题:您必须将所需的屏幕坐标放在视图投影矩阵的反转处。当您从2D到3D时,您必须添加深度信息。对不起,但我无法帮助你解决这个问题。